示例#1
0
 private static void OpenMainScene()
 {
     EditorSceneManager.OpenScene("Assets/Scenes/Main.unity");
 }
 public static void GoToFinalLevel()
 {
     EditorSceneManager.OpenScene("Assets/Scenes/FinalRevision.unity");
 }
 public void OneTimeSetUp()
 {
     EditorSceneManager.OpenScene(@"Assets\Scenes\SampleScene.unity", OpenSceneMode.Single);
     SampleScene = SceneManager.GetActiveScene();
 }
 public static void GoToMainMenuScene()
 {
     EditorSceneManager.OpenScene("Assets/Scenes/MainMenu.unity");
 }
 public static void GoToNewLevelOne()
 {
     EditorSceneManager.OpenScene("Assets/Scenes/NewLevel1.unity");
 }
示例#6
0
 static private void SceneMain()
 {
     Debug.Log("メインシーンへ移動");
     EditorSceneManager.OpenScene(string.Format("{0}{1}", Application.dataPath, "/Scenes/Main.unity"));
 }
示例#7
0
        void OnGUI()
        {
            EditorGUILayout.HelpBox("The tool will serialize scene  generating a new cooked scene and label scene assets  automatically.Then, you can use SceneBuilder tool to build these assets!", MessageType.Info);

            if (GUILayout.Button("Serialize Scene"))
            {
                string SceneOriginalName = EditorSceneManager.GetActiveScene().name;
                #region Save As New Scene
                EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene(), "Assets/Res/Cooked/Scene/" + SceneOriginalName + "_Cooked.unity", true);
                EditorSceneManager.OpenScene("Assets/Res/Cooked/Scene/" + SceneOriginalName + "_Cooked.unity");
                #endregion
                GameObject[]      SceneObjects            = GameObject.FindObjectsOfType <GameObject>();
                List <GameObject> ScenePrefabsGameObjects = new List <GameObject>();

                int SerializedID = 0;

                foreach (GameObject sceneObject in SceneObjects)
                {
                    GameObject PrefabRoot = PrefabUtility.FindRootGameObjectWithSameParentPrefab(sceneObject); //场景中物体父对象

                    if (PrefabUtility.GetPrefabType(sceneObject) != PrefabType.None)
                    {
                        if (PrefabRoot.tag == "NotAllowBuild")
                        {
                            continue;
                        }

                        if (ScenePrefabsGameObjects.Contains(PrefabRoot))
                        {
                            Debug.Log(PrefabRoot.name + "Built");
                            continue;
                        }
                        SerializedID += 1;
                        #region Genrerate new ReplaceObject with SceneAssetPrefab.cs
                        GameObject ReplaceObject = new GameObject(PrefabRoot.name + "_CookedResource");

                        ReplaceObject.transform.position   = PrefabRoot.transform.position;
                        ReplaceObject.transform.rotation   = PrefabRoot.transform.rotation;
                        ReplaceObject.transform.localScale = PrefabRoot.transform.localScale;

                        ReplaceObject.transform.SetParent(PrefabRoot.transform.parent);

                        //ReplaceObject.isStatic = PrefabRoot.isStatic;
                        //ReplaceObject.layer = PrefabRoot.layer;
                        //ReplaceObject.transform.tag = PrefabRoot.transform.tag;

                        #region SetUp SceneAssetPrefab
                        SceneAssetPrefab sceneAssetPrefab = ReplaceObject.AddComponent <SceneAssetPrefab>();
                        List <SceneAssetPrefab.MeshParameter> MeshParameters = new List <SceneAssetPrefab.MeshParameter>();
                        #region Save LightMap data
                        if (PrefabRoot.GetComponentsInChildren <ParticleSystem>().Length > 0)
                        {
                            sceneAssetPrefab.HasParticleSystem = true;
                        }

                        if (PrefabRoot.GetComponentsInChildren <MeshRenderer>().Length > 0)
                        {
                            foreach (MeshRenderer meshRender in PrefabRoot.GetComponentsInChildren <MeshRenderer>())
                            {
                                SceneAssetPrefab.MeshParameter MeshParameter = new SceneAssetPrefab.MeshParameter();
                                if (meshRender.transform == PrefabRoot.transform)
                                {
                                    MeshParameter.RendererPathinChild = false;
                                }
                                else
                                {
                                    MeshParameter.RendererPathinChild = true;
                                    Transform Current = meshRender.transform;

                                    string        ChildPath = "";
                                    List <string> Relation  = new List <string>();
                                    while (Current != PrefabRoot.transform)
                                    {
                                        Relation.Add(Current.name);
                                        Current = Current.parent;
                                    }
                                    for (int i = Relation.Count - 1; i >= 0; i--)
                                    {
                                        ChildPath += Relation[i] + "/";
                                    }
                                    MeshParameter.RendererPath = ChildPath;
                                }
                                MeshParameter.LightingMapIndex        = meshRender.lightmapIndex;
                                MeshParameter.LightingMapTilingOffset = meshRender.lightmapScaleOffset;
                                MeshParameter.reflectionusage         = meshRender.reflectionProbeUsage;
                                MeshParameters.Add(MeshParameter);
                            }
                        }

                        sceneAssetPrefab.assetName          = PrefabUtility.GetPrefabParent(PrefabRoot).name;
                        sceneAssetPrefab.meshParameters     = MeshParameters.ToArray();
                        sceneAssetPrefab.SerializedID       = SerializedID;
                        sceneAssetPrefab.assetBundleName    = AssetNameCorretor(AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(PrefabUtility.GetPrefabParent(PrefabRoot))));
                        sceneAssetPrefab.assetBundleVariant = "sceneobject";
                        #endregion
                        #endregion



                        #endregion

                        if (!ScenePrefabsGameObjects.Contains(PrefabRoot))
                        {
                            ScenePrefabsGameObjects.Add(PrefabRoot);
                        }
                    }
                }
                List <GameObject> GameObjectsInAsset = new List <GameObject>();
                foreach (GameObject scenePrefab in ScenePrefabsGameObjects)
                {
                    GameObject GameObjectInAsset = PrefabUtility.GetPrefabParent(scenePrefab) as GameObject;
                    if (!GameObjectsInAsset.Contains(GameObjectInAsset))
                    {
                        GameObjectsInAsset.Add(GameObjectInAsset);
                    }
                }

                SceneData sceneData = ScriptableObject.CreateInstance <SceneData>();
                sceneData.SceneObjectReferences = GameObjectsInAsset.ToArray();
                System.IO.DirectoryInfo Dir = System.IO.Directory.CreateDirectory("Assets/Cooks/Map/");

                AssetDatabase.CreateAsset(sceneData, "Assets/Cooks/Map/" + SceneOriginalName + ".asset");
                AssetDatabase.SaveAssets();
                EditorUtility.FocusProjectWindow();
                Selection.activeObject = sceneData;

                foreach (GameObject scenePrefab in ScenePrefabsGameObjects)
                {
                    //if (scenePrefab != null && !Reimported.Contains(PrefabUtility.GetPrefabParent(scenePrefab)))
                    //{
                    //    Reimported.Add(PrefabUtility.GetPrefabParent(scenePrefab));

                    //    Debug.Log(scenePrefab.name + "Asset Reimported!");
                    //    AssetImporter assetImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(PrefabUtility.GetPrefabParent(scenePrefab)));
                    //    string AssetPathToGUID = AssetNameCorretor(AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(PrefabUtility.GetPrefabParent(scenePrefab))));

                    //    assetImporter.assetBundleName = AssetPathToGUID;
                    //    assetImporter.assetBundleVariant = "sceneobject";


                    //}
                    DestroyImmediate(scenePrefab);
                }
                EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
                EditorSceneManager.SaveOpenScenes();
                string AllScenes = "\n Current Active Scenes:";
                bool   AddFlag   = true;

                for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
                {
                    AllScenes += "\n -" + EditorBuildSettings.scenes[i].path;
                    if (EditorBuildSettings.scenes[i].path == EditorSceneManager.GetActiveScene().path)
                    {
                        AddFlag = false;
                    }
                }
                if (AddFlag)
                {
                    if (EditorUtility.DisplayDialog("Add to BuildSetting", "Do you want to add this cooked scene to BuildSetting?" + AllScenes, "Yes", "No,Thanks"))
                    {
                        EditorBuildSettingsScene[] original    = EditorBuildSettings.scenes;
                        EditorBuildSettingsScene[] newSettings = new EditorBuildSettingsScene[original.Length + 1];
                        System.Array.Copy(original, newSettings, original.Length);
                        newSettings[newSettings.Length - 1] = new EditorBuildSettingsScene(EditorSceneManager.GetActiveScene().path, true);
                        EditorBuildSettings.scenes          = newSettings;
                    }
                }



                //EditorSceneManager.SaveOpenScenes ();
            }
        }
示例#8
0
 static void EnterEditUI()
 {
     EditorSceneManager.OpenScene("Assets/Edit/Scenes/UIEditor.unity", OpenSceneMode.Single);
     //EditorApplication.ExecuteMenuItem("Edit/Play");
 }
 public static void ReturnToLastScene()
 {
     // Read last scene path from temp file and open that scene
     EditorSceneManager.OpenScene(File.ReadAllText(".tempScenePlayScript"));
 }
示例#10
0
    public static void ReturnPreviousScene()
    {
        string lastScene = File.ReadAllText(".lastScene");

        EditorSceneManager.OpenScene("Assets/Scenes/" + lastScene + ".unity");
    }
示例#11
0
 static void RunGame()
 {
     EditorSceneManager.OpenScene("Assets/Resources/Scenes/Splash.unity", OpenSceneMode.Single);
     EditorApplication.ExecuteMenuItem("Edit/Play");
 }
示例#12
0
        void Apply(int queryIndex)
        {
            if (queryIndex >= res.Count)
            {
                return;
            }
            Close();
            UnityEngine.Object[] o = null;
            if (queryType < KeyTypes.OpenScene)
            {
                // load objects
                if (queryIndex < 0)
                {
                    if (query.Length == kMaxLists)
                    {
                        var oldk = kMaxLists;
                        kMaxLists = int.MaxValue;
                        ReloadResults(query); //full requery
                        kMaxLists = oldk;
                    }
                    o = GetObjects();
                }
                else
                {
                    o = new UnityEngine.Object[] { EditorUtility.InstanceIDToObject((int)res[queryIndex].obj) }
                };
            }
            switch (queryType)
            {
            case KeyTypes.SelectGameObject:
            case KeyTypes.SelectInChildren:
            case KeyTypes.SelectAsset:
            case KeyTypes.SelectHasTypes:
                if (queryIndex >= 0 && queryType == KeyTypes.SelectAsset)
                {
                    EditorGUIUtility.PingObject(o[0]);
                }
                Selection.objects = o;
                break;

            case KeyTypes.SelectAdditive:
                ArrayUtility.AddRange(ref o, Selection.objects);
                Selection.objects = o;
                break;

            case KeyTypes.SelectSubstractive:
                var x = new HashSet <UnityEngine.Object>(Selection.objects);
                x.ExceptWith(o);
                Selection.objects = x.ToArray();
                break;

            case KeyTypes.OpenScene:
                // Shift here means add the first result additively
                var z = res[Mathf.Max(0, queryIndex)];
                EditorSceneManager.OpenScene(z.name, queryIndex == -1 ? OpenSceneMode.Additive : OpenSceneMode.Single);
                break;

            case KeyTypes.ExecuteWindow:
                // This time obj would be a type instead of instance ID
                // index -1 (launch all) is not acceptable here
                var y = (Type)res[Mathf.Max(0, queryIndex)].obj;
                ((EditorWindow)CreateInstance(y)).Show();
                break;
            }
        }

        UnityEngine.Object[] GetObjects()
        {
            var obj = new UnityEngine.Object[res.Count];

            for (int i = 0; i < res.Count; i++)
            {
                obj[i] = EditorUtility.InstanceIDToObject((int)res[i].obj);
            }
            return(obj);
        }
示例#13
0
        void OnGUI()
        {
            GUI.backgroundColor = new Color32(0, 255, 255, 255);
            GUI.contentColor    = Color.white;

            EditorGUILayout.BeginVertical();

            GUIStyle      guiStyle   = new GUIStyle();
            GUIStyleState styleState = new GUIStyleState();

            GUI.backgroundColor = new Color(0.0f, 0.0f, 0.0f, 0.4f);

            styleState.background = Texture2D.whiteTexture;

            styleState.textColor = Color.green;

            guiStyle.normal = styleState;

            GUI.Label(new Rect(0, 0, position.width, 20), "", guiStyle);

            GUI.backgroundColor = new Color32(0, 255, 255, 255);

            EditorGUILayout.BeginHorizontal();
            {
                GUILayout.Label("Scene", GUILayout.Width(60f));
                GUILayout.Label("Path", GUILayout.Width(200f));

                GUILayout.FlexibleSpace();

                GUILayout.Label("Action", GUILayout.Width(100f));
            }
            EditorGUILayout.EndHorizontal();

            GUILayout.Space(10);

            foreach (KeyValuePair <string, string> kvp in mScenes)
            {
                EditorGUILayout.BeginHorizontal();
                {
                    EditorGUILayout.LabelField(kvp.Key, GUILayout.Width(60f));

                    EditorGUILayout.LabelField(kvp.Value, GUILayout.Width(200f));

                    GUILayout.FlexibleSpace();

                    if (SceneManager.GetActiveScene().name == kvp.Key)
                    {
                        GUI.backgroundColor = new Color32(255, 125, 130, 255);

                        if (GUILayout.Button("Save", GUILayout.Width(100f), GUILayout.Height(25f)))
                        {
                            EditorSceneManager.SaveScene(SceneManager.GetActiveScene(), kvp.Value);
                        }
                    }
                    else
                    {
                        GUI.backgroundColor = new Color32(0, 255, 255, 255);

                        if (GUILayout.Button("Load", GUILayout.Width(100f), GUILayout.Height(25f)))
                        {
                            EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo();
                            EditorSceneManager.OpenScene(kvp.Value);
                        }
                    }
                }
                EditorGUILayout.EndHorizontal();
            }

            GUI.backgroundColor = new Color32(0, 255, 255, 255);

            GUILayout.FlexibleSpace();

            EditorGUILayout.BeginHorizontal();

            GUILayout.FlexibleSpace();

            if (GUILayout.Button("Refresh", GUILayout.Width(position.width - 20), GUILayout.Height(25f)))
            {
                Refresh();
            }

            GUILayout.FlexibleSpace();

            EditorGUILayout.EndHorizontal();

            GUILayout.Space(10);

            EditorGUILayout.EndVertical();
        }
示例#14
0
        /*public static void OpenScenes(string name)
         * {
         *  OCSceneConfig config = OCGenerator.GetSceneConfig(name);
         *  string path = config.GetSceneAssetPath();
         *  path += "/";
         *
         *
         *  if (config.IsStreamScene)
         *  {
         *      int tileDim = config.TileDimension;
         *      int tileSize = config.TileSize;
         *
         *      var mainScene = SceneManager.GetSceneByName("AdditiveScene.unity");
         *      if(mainScene.isLoaded == false)
         *          EditorSceneManager.OpenScene(path + "AdditiveScene.unity", OpenSceneMode.Additive);
         *
         *      foreach (var index in config.indices)
         *      {
         *          string sceneName = string.Format("{0} {1}x{2}", name, index.x , index.y);
         *          string scenePath = path + sceneName + ".unity";
         *
         *          var scene = SceneManager.GetSceneByName(sceneName);
         *          if (scene.isLoaded == false)
         *              EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive);
         *      }
         *
         *  }
         *  else
         *  {
         *      EditorSceneManager.OpenScene(path + name +".unity");
         *  }
         * }*/

        public static void GenerateTestStreamScenes(string name)
        {
            OCSceneConfig config = OCGenerator.GetSceneConfig(name);
            string        path   = config.GetSceneAssetPath();

            path += "/";

            int tileDim  = config.TileDimension;
            int tileSize = config.TileSize;

            var template = Resources.Load("root") as GameObject;

            var mainScene = EditorSceneManager.OpenScene(path + "AdditiveScene.unity");

            foreach (var root in mainScene.GetRootGameObjects())
            {
                GameObject.DestroyImmediate(root);
            }
            var mainCamera = Resources.Load("MainCamera") as GameObject;
            var cam        = GameObject.Instantiate(mainCamera);


            for (int i = 0; i < tileDim; i++)
            {
                for (int j = 0; j < tileDim; j++)
                {
                    string sceneName = string.Format("{0} {1}x{2}", name, i, j);
                    string scenePath = path + sceneName + ".unity";
                    var    scene     = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Additive);

                    EditorSceneManager.SetActiveScene(scene);

                    foreach (var root in scene.GetRootGameObjects())
                    {
                        GameObject.DestroyImmediate(root);
                    }

                    var templateGO = GameObject.Instantiate(template);
                    templateGO.transform.localScale = new Vector3(tileSize / 10, tileSize / 10, tileSize / 10);
                    templateGO.transform.position   = new Vector3(i * tileSize, 0, j * tileSize);
                    var     pos         = templateGO.transform.position;
                    float   offsetValue = -tileSize * tileDim * 0.5f;
                    Vector3 offset      = new Vector3(offsetValue, 0, offsetValue);
                    templateGO.transform.position = pos + offset;

                    var coms = templateGO.GetComponentsInChildren <MeshRenderer>();

                    int count = 0;
                    foreach (var com in coms)
                    {
                        var idcom = com.gameObject.GetComponent <GameObjectID>();
                        if (idcom == null)
                        {
                            idcom = com.gameObject.AddComponent <GameObjectID>();
                        }

                        idcom.GUID = count;
                        count++;
                    }

                    EditorSceneManager.SaveScene(scene);
                }
            }

            //EditorSceneManager.SaveOpenScenes();
        }
 public void OpenSceneAndSetUpCriterion()
 {
     EditorSceneManager.OpenScene(GetTestAssetPath("EmptyTestScene.unity"));
     SaveActiveScene();
 }
示例#16
0
 private static void OpenScene(Scene scene)
 {
     EditorSceneManager.OpenScene(scene.path, OpenSceneMode.Additive);
 }
        public bool ScanScenes(string[] scenePaths, bool includeSceneDependencies, bool showProgressBar)
        {
            if (scenePaths.Length == 0)
            {
                return(true);
            }

            bool formerForceEditorModeSerialization = UnitySerializationUtility.ForceEditorModeSerialization;

            try
            {
                UnitySerializationUtility.ForceEditorModeSerialization = true;

                bool hasDirtyScenes = false;

                for (int i = 0; i < EditorSceneManager.sceneCount; i++)
                {
                    if (EditorSceneManager.GetSceneAt(i).isDirty)
                    {
                        hasDirtyScenes = true;
                        break;
                    }
                }

                if (hasDirtyScenes && !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
                {
                    return(false);
                }

                var oldSceneSetup = EditorSceneManager.GetSceneManagerSetup();

                try
                {
                    for (int i = 0; i < scenePaths.Length; i++)
                    {
                        var scenePath = scenePaths[i];

                        if (showProgressBar && DisplaySmartUpdatingCancellableProgressBar("Scanning scenes for AOT support", "Scene " + (i + 1) + "/" + scenePaths.Length + " - " + scenePath, (float)i / scenePaths.Length))
                        {
                            return(false);
                        }

                        if (!System.IO.File.Exists(scenePath))
                        {
                            Debug.LogWarning("Skipped AOT scanning scene '" + scenePath + "' for a file not existing at the scene path.");
                            continue;
                        }

                        Scene openScene = default(Scene);

                        try
                        {
                            openScene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);
                        }
                        catch
                        {
                            Debug.LogWarning("Skipped AOT scanning scene '" + scenePath + "' for throwing exceptions when trying to load it.");
                            continue;
                        }

                        var sceneGOs = Resources.FindObjectsOfTypeAll <GameObject>();

                        foreach (var go in sceneGOs)
                        {
                            if (go.scene != openScene)
                            {
                                continue;
                            }

                            if ((go.hideFlags & HideFlags.DontSaveInBuild) == 0)
                            {
                                foreach (var component in go.GetComponents <ISerializationCallbackReceiver>())
                                {
                                    try
                                    {
                                        this.allowRegisteringScannedTypes = true;
                                        component.OnBeforeSerialize();

                                        var prefabSupporter = component as ISupportsPrefabSerialization;

                                        if (prefabSupporter != null)
                                        {
                                            // Also force a serialization of the object's prefab modifications, in case there are unknown types in there

                                            List <UnityEngine.Object> objs = null;
                                            var mods = UnitySerializationUtility.DeserializePrefabModifications(prefabSupporter.SerializationData.PrefabModifications, prefabSupporter.SerializationData.PrefabModificationsReferencedUnityObjects);
                                            UnitySerializationUtility.SerializePrefabModifications(mods, ref objs);
                                        }
                                    }
                                    finally
                                    {
                                        this.allowRegisteringScannedTypes = false;
                                    }
                                }
                            }
                        }
                    }

                    // Load a new empty scene that will be unloaded immediately, just to be sure we completely clear all changes made by the scan
                    // Sometimes this fails for unknown reasons. In that case, swallow any exceptions, and just soldier on and hope for the best!
                    // Additionally, also eat any debug logs that happen here, because logged errors can stop the build process, and we don't want
                    // that to happen.

                    UnityEngine.ILogger logger = null;

                    if (Debug_Logger_Property != null)
                    {
                        logger = (UnityEngine.ILogger)Debug_Logger_Property.GetValue(null, null);
                    }

                    bool previous = true;

                    try
                    {
                        if (logger != null)
                        {
                            previous          = logger.logEnabled;
                            logger.logEnabled = false;
                        }

                        EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
                    }
                    catch { }
                    finally
                    {
                        if (logger != null)
                        {
                            logger.logEnabled = previous;
                        }
                    }
                }
                finally
                {
                    if (oldSceneSetup != null && oldSceneSetup.Length > 0)
                    {
                        if (showProgressBar)
                        {
                            EditorUtility.DisplayProgressBar("Restoring scene setup", "", 1.0f);
                        }
                        EditorSceneManager.RestoreSceneManagerSetup(oldSceneSetup);
                    }
                }

                if (includeSceneDependencies)
                {
                    for (int i = 0; i < scenePaths.Length; i++)
                    {
                        var scenePath = scenePaths[i];
                        if (showProgressBar && DisplaySmartUpdatingCancellableProgressBar("Scanning scene dependencies for AOT support", "Scene " + (i + 1) + "/" + scenePaths.Length + " - " + scenePath, (float)i / scenePaths.Length))
                        {
                            return(false);
                        }

                        string[] dependencies = AssetDatabase.GetDependencies(scenePath, recursive: true);

                        foreach (var dependency in dependencies)
                        {
                            this.ScanAsset(dependency, includeAssetDependencies: false); // All dependencies of this asset were already included recursively by Unity
                        }
                    }
                }

                return(true);
            }
            finally
            {
                if (showProgressBar)
                {
                    EditorUtility.ClearProgressBar();
                }

                UnitySerializationUtility.ForceEditorModeSerialization = formerForceEditorModeSerialization;
            }
        }
示例#18
0
 private static void OpenScene(string sceneName)
 {
     EditorSceneManager.OpenScene("Assets/Scenes/PersistentScene.unity", OpenSceneMode.Single);
     EditorSceneManager.OpenScene("Assets/Scenes/" + sceneName + ".unity", OpenSceneMode.Additive);
 }
示例#19
0
        void OnGUI()
        {
            InitStyles();

            styleHelpboxInner         = new GUIStyle("HelpBox");
            styleHelpboxInner.padding = new RectOffset(6, 6, 6, 6);
            scrollPos = EditorGUILayout.BeginScrollView(scrollPos, false, false, GUILayout.Width(position.width), GUILayout.Height(position.height));
            GUILayout.BeginHorizontal(styleHelpboxInner);
            GUILayout.FlexibleSpace();
            GUILayout.Label("All scenes that are in the Scenes folder", titleLabel);
            if (GUILayout.Button(new GUIContent("?", "Shoot me an email about the issue or suggestions"), helpButtonStyle, GUILayout.MaxWidth(20), GUILayout.MaxHeight(20)))
            {
                Application.OpenURL("https://github.com/prashant-singh");
            }
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();
            GUILayout.BeginVertical(styleHelpboxInner);
            GetSceneNames();
            if (sceneData.Count == 0)
            {
                GUILayout.Label("No scenes in the Scenes folder.", titleLabel);
            }
            else
            {
                for (int count = 0; count < sceneData.Count; count++)
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.FlexibleSpace();

                    if (!editModesOfScenes[count])
                    {
                        newNames[count] = sceneData[count].sceneName;
                        if (sceneData[count].isAddedToBuildSettings)
                        {
                            if (GUILayout.Button(sceneData[count].sceneName, editorAddedButtonStyle, GUILayout.MinWidth(200), GUILayout.MaxWidth(1000), GUILayout.Height(20)))
                            {
#if UNITY_5
                                if (EditorApplication.SaveCurrentSceneIfUserWantsTo())
                                {
                                    EditorApplication.OpenScene(sceneData[count].scenePath + "/" + sceneData[count].sceneName + ".unity");
                                }
#endif
                                if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
                                {
                                    EditorSceneManager.OpenScene(sceneData[count].scenePath + "/" + sceneData[count].sceneName + ".unity");
                                }
                            }
                        }
                        else
                        {
                            if (GUILayout.Button(sceneData[count].sceneName, normalButtonStyle, GUILayout.MinWidth(200), GUILayout.MaxWidth(1000), GUILayout.Height(20)))
                            {
#if UNITY_5
                                if (EditorApplication.SaveCurrentSceneIfUserWantsTo())
                                {
                                    EditorApplication.OpenScene(sceneData[count].scenePath + "/" + sceneData[count].sceneName + ".unity");
                                }
#endif
                                if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
                                {
                                    EditorSceneManager.OpenScene(sceneData[count].scenePath + "/" + sceneData[count].sceneName + ".unity");
                                }
                            }
                        }

                        if (GUILayout.Button(editButtonIcon, normalButtonStyle, GUILayout.Width(30), GUILayout.Height(20)))
                        {
                            newNames[count]          = sceneData[count].sceneName;
                            editModesOfScenes[count] = true;
                            ResetAllEditings(count);
                            isEditModeOpen = true;
                        }
                    }
                    else
                    {
                        newNames[count] = GUILayout.TextField(newNames[count], GUILayout.Width(200), GUILayout.Height(20));
                        if (GUILayout.Button(saveButtonIcon, GUILayout.Width(30), GUILayout.Height(20)))
                        {
                            var dirInfo      = new DirectoryInfo(Application.dataPath + "/Scenes");
                            var allFileInfos = dirInfo.GetFiles("*.unity", SearchOption.AllDirectories);
                            foreach (var fileInfo in allFileInfos)
                            {
                                if (fileInfo.Name.Equals(sceneData[count].sceneName + ".unity"))
                                {
                                    AssetDatabase.RenameAsset("Assets/Scenes/" + sceneData[count].sceneName + ".unity", newNames[count]);
                                    AssetDatabase.Refresh();
                                    editModesOfScenes[count] = false;
                                    isEditModeOpen           = false;
                                }
                            }
                        }
                    }
                    GUILayout.FlexibleSpace();
                    GUILayout.EndHorizontal();
                }
            }

            GUILayout.EndVertical();
            GUILayout.EndScrollView();
        }
示例#20
0
        public static void OpenLevel(GameLevel targetGameLevel, bool includeMasterScene, bool keepCurrentScenesThatAreOpenOpeneded, bool includeDependencies)
        {
            List <Scene> loadedScenes = new List <Scene>();

            for (int i = 0; i < SceneManager.sceneCount; i++)
            {
                loadedScenes.Add(SceneManager.GetSceneAt(i));
            }
            Scene[] loadedScenesArray = loadedScenes.ToArray();
            EditorSceneManager.SaveModifiedScenesIfUserWantsTo(loadedScenesArray);

            //Load The Master Scene
            if (includeMasterScene == true)
            {
                string masterScenePath = "Assets/" + GameLevelToolkitWindow.GetProjectPathStringWithSlash() + "Scenes/" + SceneAndResourceFolderName.folderNameValue + "/Master Scene/Master Scene.unity";
                Scene  masterScene;

                if (keepCurrentScenesThatAreOpenOpeneded == true)
                {
                    masterScene = EditorSceneManager.OpenScene(masterScenePath, OpenSceneMode.Additive);
                }
                else
                {
                    masterScene = EditorSceneManager.OpenScene(masterScenePath, OpenSceneMode.Single);
                }

                EditorSceneManager.SetActiveScene(masterScene);
            }

            //Unload Any Existing Scenes If Required
            if (includeMasterScene == false && keepCurrentScenesThatAreOpenOpeneded == false)
            {
                for (int i = 0; i < SceneManager.sceneCount; i++)
                {
                    Scene scene = SceneManager.GetSceneAt(i);
                    if (!IsActiveScene(scene))
                    {
                        CloseScene(scene);
                    }
                    if (scene.name == "Master Scene")
                    {
                        if (!IsActiveScene(scene))
                        {
                            EditorSceneManager.SetActiveScene(scene);
                        }
                    }
                }
            }

            //Load The Locations Scenes
            LoadLocationsScenesAdditively(targetGameLevel);

            //Load Dependencies If Required
            if (includeDependencies == true)
            {
                for (int i = 0; i < targetGameLevel.levelDependencies.Count; i++)
                {
                    LoadLocationsScenesAdditively(targetGameLevel.levelDependencies[i]);
                }
            }
        }
 public static void GoToRootScene()
 {
     EditorSceneManager.OpenScene("Assets/Scenes/Root.unity");
 }
示例#22
0
    public static void ExportBundle(string source)
    {
        string dest = Path.Combine(ModManager.GetModsfolderPath(), $"modfile_{Path.GetFileName(source)}");

        Debug.Log($"Exporting Mod: Source: \"{source}\", Target: \"{dest}\"");

        // Get Files and convert absolute paths to relative paths (required by the buildmap)
        string[] absolute_files = Directory.GetFiles(source).Where(name => !name.EndsWith(".meta") && !name.EndsWith(".cs")).ToArray();
        string[] files          = new string[absolute_files.Length];

        if (files.Length > 0)
        {
            int index = absolute_files[0].IndexOf("Assets");
            for (int i = 0; i < files.Length; i++)
            {
                files[i] = absolute_files[i].Substring(index);
            }
        }

        if (!CheckHasHolder(files))
        {
            throw new System.Exception($"Failed to export \"{Path.GetDirectoryName(source)}\". Make sure you have an appropriate holder included!");
        }

        // Prepare Bundle
        AssetBundleBuild[] build_map = new AssetBundleBuild[1];
        build_map[0].assetNames = files;

        // Build Folder / Bundle
        Directory.CreateDirectory(dest);
        foreach (var target in new Dictionary <OperatingSystemFamily, BuildTarget> {
            { OperatingSystemFamily.Windows, BuildTarget.StandaloneWindows64 }, { OperatingSystemFamily.Linux, BuildTarget.StandaloneLinux64 }, { OperatingSystemFamily.MacOSX, BuildTarget.StandaloneOSX }
        })
        {
            build_map[0].assetBundleName = $"{Path.GetFileName(source)}_{target.Key}";
            BuildPipeline.BuildAssetBundles(dest, build_map, BuildAssetBundleOptions.None, target.Value);
        }

        // Clean out manifest files and bundle holder
        try {
            if (Directory.GetFiles(dest).Count() > 10)  // FAILSAFE
            {
                throw new System.ArgumentException($"failsafe triggered: too many files found in mod folder! Skipping deletion of unneeded files!");
            }

            File.Delete(Path.Combine(dest, Path.GetFileName(dest)));
            foreach (var manifest in Directory.GetFiles(dest, "*.manifest", SearchOption.TopDirectoryOnly))
            {
                File.Delete(Path.Combine(dest, manifest));
            }
        } catch (System.UnauthorizedAccessException) {
            Debug.LogWarning("Unauthorized to delete obsolete files in the exported mod. These files are not needed and don't need to be removed manually.");
        } catch (System.ArgumentException e) {
            Debug.LogError(e);
        }

        // Make Thumbnail
        GameObject thumbnailMakerPrefab = UnityEditor.AssetDatabase.LoadAssetAtPath <GameObject>("Assets/ThumbnailMaker.prefab");

        if (thumbnailMakerPrefab)
        {
            Mod mod = ModImporter.ImportModNow(dest, true);

            string lastScene      = EditorSceneManager.GetActiveScene().path;
            int    lastBuildIndex = EditorSceneManager.GetActiveScene().buildIndex;

            // Create scene
            Scene          thumbnailScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
            ThumbnailMaker thumbnailMaker = Instantiate(thumbnailMakerPrefab).GetComponent <ThumbnailMaker>();

            File.WriteAllBytes(mod.GetThumbnailPath(), thumbnailMaker.CreateThumbnail(mod).EncodeToJPG(90));
            // Cleanup
            if (lastBuildIndex >= 0)
            {
                EditorSceneManager.OpenScene(lastScene, OpenSceneMode.Single);
            }
            else
            {
                EditorSceneManager.OpenScene(EditorSceneManager.GetSceneByBuildIndex(0).path);
            }
        }

        Debug.Log($"Export Completed. Name: \"{Path.GetFileName(source)}\" with {files.Length} files");
    }
 public static void GoToTutorialScene()
 {
     EditorSceneManager.OpenScene("Assets/Scenes/Tutorial.unity");
 }
示例#24
0
        void OnGUI()
        {
            if (projectList == null)
            {
                projectList = new ReorderableList(scenesInProject, typeof(SceneInfo), false, false, false, false);
                projectList.drawHeaderCallback =
                    (Rect rect) =>
                {
                    EditorGUI.LabelField(rect, "Scenes In Project", EditorStyles.boldLabel);
                };
                projectList.drawElementCallback =
                    (Rect rect, int index, bool isActive, bool isFocused) =>
                {
                    var sceneInfo = scenesInProject[index];
                    EditorGUI.LabelField(new Rect(rect.x, rect.y, rect.width - 60, rect.height), sceneInfo.name);
                    if (GUI.Button(new Rect(rect.width - 60, rect.y, 20, rect.height), "P", GUIStyle.none))
                    {
                        EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath <SceneAsset>(sceneInfo.path));
                    }
                    if (GUI.Button(new Rect(rect.width - 40, rect.y, 20, rect.height), "O", GUIStyle.none))
                    {
                        List <SceneInfo> scenes = this.GetScenesInHierarchy();                               //得到 Hierarchy 中的 已加载的 场景
                        int sceneIndex          = scenes.FindIndex(v => v.path == sceneInfo.path);           //确认当前请求添加的场景 的状态
                        if (sceneIndex == -1)
                        {
                            bool savemodified = EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo();
                            if (savemodified) //After the user responds positively (with or without saving), open the scene he specified.
                            {
                                int switchIndex = EditorUtility.DisplayDialogComplex("OpenSceneMode", "Addition:Add scene and keep the loaded scene\nSingle:Will Remove all the loaded scene of hierarchy", "Single", "Cancel", "Addition");
                                switch (switchIndex)
                                {
                                case 0:
                                    EditorSceneManager.OpenScene(sceneInfo.path);
                                    break;

                                case 2:
                                    EditorSceneManager.OpenScene(sceneInfo.path, OpenSceneMode.Additive);
                                    break;

                                case 1:
                                default:
                                    this.ShowNotification(new GUIContent("Aborting!"));
                                    break;
                                }
                            }
                            else
                            {
                                this.ShowNotification(new GUIContent("Aborting!"));
                            }
                        }
                        else                          //If it is stay in the hierarchy,no matter whether it is load or unload, ping this scene
                        {
                            EditorGUIUtility.PingObject(scenes[sceneIndex].instanceID);
                            this.ShowNotification(new GUIContent("This scene already in the hierarchy!"));
                        }
                    }
                    if (GUI.Button(new Rect(rect.width - 20, rect.y, 20, rect.height), "A", GUIStyle.none))
                    {
                        int sceneIndex = SceneUtility.GetBuildIndexByScenePath(sceneInfo.path);
                        if (sceneIndex == -1)
                        {
                            var tmpSceneIn = EditorBuildSettings.scenes.ToList();
                            tmpSceneIn.Add(new EditorBuildSettingsScene(sceneInfo.path, true));
                            EditorBuildSettings.scenes = tmpSceneIn.ToArray();
                            ADB.Refresh();
                        }
                        else
                        {
                            this.ShowNotification(new GUIContent("This scene already in the buildlist!"));
                        }
                    }
                };
            }
            if (settingList == null)
            {
                settingList = new ReorderableList(scenesInSettings, typeof(SceneInfo), true, false, false, true);
                settingList.onReorderCallback =
                    (ReorderableList list) =>
                {
                    EditorBuildSettings.scenes =
                        list.list.Cast <SceneInfo>()
                        .Select(scene =>
                    {
                        var editorScene     = new EditorBuildSettingsScene();
                        editorScene.enabled = scene.enabledInSettings;
                        editorScene.path    = scene.path;
                        return(editorScene);
                    })
                        .ToArray();
                };
                settingList.drawHeaderCallback =
                    (Rect rect) =>
                {
                    EditorGUI.LabelField(rect, "Scenes In Setting", EditorStyles.boldLabel);
                };
                settingList.drawElementCallback =
                    (Rect rect, int index, bool isActive, bool isFocused) =>
                {
                    var sceneInfo = scenesInSettings[index];
                    sceneInfo.enabledInSettings = GUI.Toggle(new Rect(rect.x, rect.y, 14, rect.height), sceneInfo.enabledInSettings, string.Empty);
                    var tmpScenesInSetting = EditorBuildSettings.scenes.ToList();
                    tmpScenesInSetting.Where(scene => scene.path == sceneInfo.path).First().enabled = sceneInfo.enabledInSettings;
                    EditorGUI.LabelField(new Rect(rect.x + 14, rect.y, rect.width - 34, rect.height), sceneInfo.name);
                    EditorGUI.LabelField(new Rect(rect.width - 8, rect.y, 20, rect.height), index.ToString());

                    if (GUI.Button(new Rect(rect.width - 65, rect.y, 20, rect.height), "PH", GUIStyle.none))
                    {
                        int id = this.GetInstanceId(sceneInfo);
                        if (id != -1)
                        {
                            RemoveNotification();
                            EditorGUIUtility.PingObject(id);
                        }
                        else
                        {
                            ShowNotification(new GUIContent("The scene you pinged is not in hierarchy!"));
                        }
                    }
                    if (GUI.Button(new Rect(rect.width - 30, rect.y, 20, rect.height), "PP", GUIStyle.none))
                    {
                        var assetObj = ADB.LoadAssetAtPath <SceneAsset>(sceneInfo.path);
                        if (null != assetObj)
                        {
                            RemoveNotification();
                            EditorGUIUtility.PingObject(assetObj);
                        }
                    }
                };
                settingList.onRemoveCallback = (ReorderableList list) =>
                {
                    if (EditorUtility.DisplayDialog("Attention:", "Really want to remove this scene from the BuildList?", "Yes", "No"))
                    {
                        var tempList = EditorBuildSettings.scenes.ToList();
                        tempList.RemoveAt(list.index);
                        tempList.TrimExcess();
                        EditorBuildSettings.scenes = tempList.ToArray();
                        ReorderableList.defaultBehaviours.DoRemoveButton(list);
                    }
                };
            }
            scenesInProject  = GetScenesInProject();
            scenesInSettings = GetScenesInSettings();

            projectList.list = scenesInProject;
            settingList.list = scenesInSettings;

            // settingScrollPosition = EditorGUILayout.BeginScrollView(settingScrollPosition);
            settingList.DoLayoutList();
            //EditorGUILayout.EndScrollView();

            projectScrollPosition = EditorGUILayout.BeginScrollView(projectScrollPosition);
            projectList.DoLayoutList();
            EditorGUILayout.EndScrollView();
        }
 public static void GoToLevelTwo()
 {
     EditorSceneManager.OpenScene("Assets/Scenes/Level2.unity");
 }
    public override void OnInspectorGUI()
    {
        if (EditorApplication.isPlaying)
        {
            return;
        }
        bool       reconstruct = false;
        LevelAsset myTarget    = (LevelAsset)target;

        var editorModeCached = editorMode;

        string[] editorModeOptions = { "Select", "Add" };
        if (GUILayout.Button("Play Level"))
        {
            DestroyLevel();
            EditorApplication.isPlaying = false;
            EditorSceneManager.OpenScene("Assets/Scenes/LevelScene.unity");
            var gameBoard = GameObject.Find("GameBoard").GetComponent <GameBoard> ();
            gameBoard.levelOverride     = myTarget;
            EditorApplication.isPlaying = true;
        }
        myTarget.isMasterPuzzle = EditorGUILayout.Toggle("IsMasterPuzzle:", myTarget.isMasterPuzzle);
        editorMode       = (EditorMode)EditorGUILayout.Popup("Mode", (int)editorMode, editorModeOptions);
        myTarget.picture = EditorGUILayout.ObjectField("GoalTexture", myTarget.picture, typeof(Texture), false) as Texture;
        if (GUILayout.Button("Clear Nodes"))
        {
            myTarget.subPuzzleNodes.Clear();
            myTarget.subPuzzleNodes.Add(new LevelAsset.SubPuzzleNode("0"));
            reconstruct = true;
        }

        if (editorModeCached != editorMode)
        {
            reconstruct = true;
        }

        if (cameraGameObject != null)
        {
            EditorGUI.DrawPreviewTexture(new Rect(0 + windowOffset.x, 0 + windowOffset.y, windowSize.x, windowSize.y), editorRenderTexture);
        }

        var selectionId = "0";

        if (editorMode == EditorMode.Select && !string.IsNullOrEmpty(selectableNodeId))
        {
            selectionId = selectableNodeId;
        }
        if (!string.IsNullOrEmpty(selectableNodeId))
        {
            EditorGUILayout.BeginVertical();
            GUILayout.Space(windowOffset.y + windowSize.y);

            var selectedNodeAsset = LevelAssetHelper.GetNodeAsset(nodeAssetDictionary, selectableNodeId);
            EditorGUILayout.BeginHorizontal();
            EditorGUILayout.LabelField("SelectionId:");
            EditorGUILayout.LabelField(selectionId);
            EditorGUILayout.EndHorizontal();

            var puzzlePivotAsset = selectedNodeAsset.puzzlePivots [selectablePuzzlePivotId];
            puzzlePivotAsset.numberOfPieces        = EditorGUILayout.Vector2Field("Number of Pieces:", puzzlePivotAsset.numberOfPieces);
            puzzlePivotAsset.type                  = (PuzzlePivotType)EditorGUILayout.EnumPopup("Type:", puzzlePivotAsset.type);
            selectedNodeAsset.collectable.isActive = EditorGUILayout.Toggle("Has Collectable:", selectedNodeAsset.collectable.isActive);
            if (selectedNodeAsset.collectable.isActive)
            {
                selectedNodeAsset.collectable.position = EditorGUILayout.Vector2Field("Position of collectable:", selectedNodeAsset.collectable.position);
                selectedNodeAsset.collectable.scale    = EditorGUILayout.Vector2Field("Scale of collectable:", selectedNodeAsset.collectable.scale);
            }

            EditorGUILayout.EndVertical();
            if (GUILayout.Button("Add PuzzlePivot"))
            {
                selectedNodeAsset.puzzlePivots.Add(new LevelAsset.PuzzlePivot());
                reconstruct = true;
            }
            if (GUILayout.Button("Add Node"))
            {
                myTarget.subPuzzleNodes.Add(new LevelAsset.SubPuzzleNode(selectedNodeAsset.id + "-" + LevelAssetHelper.GetChildrenNodes(nodeAssetDictionary, selectedNodeAsset.id).Count));
                reconstruct = true;
            }
        }

        var tmpMousePos = Event.current.mousePosition;

        tmpMousePos -= windowOffset;
        tmpMousePos -= windowSize * 0.5f;
        if (Event.current.type == EventType.MouseDown && IsPositionWithinWindow(Event.current.mousePosition))
        {
            if (editorMode == EditorMode.Select)
            {
                var mousePosInWindow = new Vector3(tmpMousePos.x / 50, -tmpMousePos.y / 50, 0);
                var hits             = Physics.RaycastAll(cameraGameObject.transform.position + mousePosInWindow, Vector3.forward, 200);
                selectableNodeId = String.Empty;
                if (hits.Length > 0)
                {
                    if (hits [0].collider.gameObject.GetComponent <LevelEditorNode> () != null)
                    {
                        selectableNodeId = hits[0].collider.gameObject.GetComponent <LevelEditorNode>().nodeId;
                    }
                    if (hits [0].collider.gameObject.GetComponent <LevelEditorPuzzlePivot> () != null)
                    {
                        var levelEditorPuzzlePivot = hits [0].collider.gameObject.GetComponent <LevelEditorPuzzlePivot> ();
                        selectableNodeId        = levelEditorPuzzlePivot.parent.nodeId;
                        selectablePuzzlePivotId = levelEditorPuzzlePivot.parent.puzzlePivots.IndexOf(levelEditorPuzzlePivot);
                    }
                }
                reconstruct = true;
            }
        }

        if (Event.current.button == 2)
        {
            if (Event.current.type == EventType.MouseDown)
            {
                mousePos = Event.current.mousePosition;
            }
            if (Event.current.type == EventType.MouseDrag)
            {
                var mouseDir = (mousePos - Event.current.mousePosition) * 0.02f;
                cameraGameObject.transform.position += new Vector3(mouseDir.x, -mouseDir.y, 0);
                mousePos = Event.current.mousePosition;
            }
        }

        if (reconstruct)
        {
            DestroyLevel();
            ConstructLevel();
        }

        EditorUtility.SetDirty(myTarget);
    }
示例#27
0
 private static void OpenScene(string scenePath)
 {
     EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo();
     EditorSceneManager.OpenScene(scenePath);
 }
示例#28
0
    private void OnGUI()
    {
        GUIStyle readLevelsButton = new GUIStyle("button");

        readLevelsButton.fontSize  = 15;
        readLevelsButton.fontStyle = FontStyle.Bold;
        GUILayout.Space(20);
        if (GUILayout.Button("Read level list", readLevelsButton, GUILayout.Height(30)))
        {
            //Debug.Log("Go");
            buildScenes = ReadScenes();
        }
        GUILayout.Label("Levels", EditorStyles.boldLabel);
        if (buildScenes.Count <= 0)
        {
            GUILayout.Label("No Levels", EditorStyles.boldLabel);
        }
        else
        {
            //create the lsit of levels in the build settings

            for (int i = 0; i < buildScenes.Count; i++)
            {
                EditorGUILayout.BeginHorizontal();
                //Take the path of the scene and only take the name of the scene
                string sceneName = buildScenes[i].path.Substring(buildScenes[i].path.LastIndexOf('/') + 1);
                sceneName = sceneName.Remove(sceneName.IndexOf(".unity"));
                //write the name
                GUILayout.Label("   " + sceneName, GUILayout.MaxWidth(200), GUILayout.MinWidth(50));
                //Go to the scene in editor button
                GUILayout.FlexibleSpace();
                if (GUILayout.Button("Go to", GUILayout.Width(70), GUILayout.Height(20)))
                {
                    EditorSceneManager.OpenScene(buildScenes[i].path);
                }
                EditorGUILayout.EndHorizontal();
            }
        }

        GUILayout.FlexibleSpace();
        if (GUILayout.Button("Create new scene", GUILayout.Width(120), GUILayout.Height(30)))
        {
            PopupWindow.Show(new Rect(), new CreateScenePopup());
        }

        EditorGUILayout.LabelField("", GUI.skin.horizontalSlider);
        showSettings = EditorGUILayout.Foldout(showSettings, "Settings");

        if (showSettings)
        {
            if (!PlayerPrefs.HasKey(SOURCE))
            {
                PlayerPrefs.SetString(SOURCE, "");
            }
            sourceScenePath = PlayerPrefs.GetString(SOURCE);
            if (!PlayerPrefs.HasKey(DESTINATION))
            {
                PlayerPrefs.SetString(SOURCE, "");
            }
            destinationScenePath = PlayerPrefs.GetString(DESTINATION);
            EditorGUILayout.BeginHorizontal();

            GUILayout.Label("Source scene: ", EditorStyles.boldLabel, GUILayout.Width(130));
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Browse", GUILayout.Width(70)))
            {
                sourceScenePath = EditorUtility.OpenFilePanel("Scene File", "", "unity");
            }
            if (sourceScenePath != string.Empty)
            {
                PlayerPrefs.SetString(SOURCE, sourceScenePath);
            }

            EditorGUILayout.EndHorizontal();
            GUILayout.Space(3);
            GUILayout.Label(sourceScenePath);

            GUILayout.Space(10);

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("Destination path: ", EditorStyles.boldLabel, GUILayout.Width(130));
            GUILayout.FlexibleSpace();
            if (GUILayout.Button("Browse", GUILayout.Width(70)))
            {
                destinationScenePath = EditorUtility.OpenFolderPanel("Scene Destination", "", "");
            }
            if (destinationScenePath != string.Empty)
            {
                PlayerPrefs.SetString(DESTINATION, destinationScenePath);
            }
            EditorGUILayout.EndHorizontal();
            GUILayout.Space(3);
            GUILayout.Label(destinationScenePath);
        }
    }
示例#29
0
 static void EditorMenu_LoadGameScene()
 {
     EditorSceneManager.OpenScene("Assets/Scenes/GameScene.unity");
 }
示例#30
0
        internal static System.Tuple <Scene, SceneAsset> Instantiate(SceneTemplateAsset sceneTemplate, bool loadAdditively, string newSceneOutputPath, SceneTemplateAnalytics.SceneInstantiationType instantiationType)
        {
            if (!sceneTemplate.IsValid)
            {
                throw new Exception("templateScene is empty");
            }

            var sourceScenePath = AssetDatabase.GetAssetPath(sceneTemplate.templateScene);

            if (String.IsNullOrEmpty(sourceScenePath))
            {
                throw new Exception("Cannot find path for sceneTemplate: " + sceneTemplate.ToString());
            }

            if (!Application.isBatchMode && !loadAdditively && !EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
            {
                return(null);
            }

            var instantiateEvent = new SceneTemplateAnalytics.SceneInstantiationEvent(sceneTemplate, instantiationType)
            {
                additive = loadAdditively
            };

            sceneTemplate.UpdateDependencies();
            var hasAnyCloneableDependencies = sceneTemplate.dependencies.Any(dep => dep.instantiationMode == TemplateInstantiationMode.Clone);

            SceneAsset newSceneAsset = null;
            Scene      newScene;

            var templatePipeline = sceneTemplate.CreatePipeline();

            if (hasAnyCloneableDependencies)
            {
                if (!InstantiateScene(sceneTemplate, sourceScenePath, ref newSceneOutputPath))
                {
                    instantiateEvent.isCancelled = true;
                    SceneTemplateAnalytics.SendSceneInstantiationEvent(instantiateEvent);
                    return(null);
                }

                templatePipeline?.BeforeTemplateInstantiation(sceneTemplate, loadAdditively, newSceneOutputPath);
                newSceneTemplateInstantiating?.Invoke(sceneTemplate, newSceneOutputPath, loadAdditively);

                var refPathMap = new Dictionary <string, string>();
                var refMap     = CopyCloneableDependencies(sceneTemplate, newSceneOutputPath, ref refPathMap);

                newScene      = EditorSceneManager.OpenScene(newSceneOutputPath, loadAdditively ? OpenSceneMode.Additive : OpenSceneMode.Single);
                newSceneAsset = AssetDatabase.LoadAssetAtPath <SceneAsset>(newSceneOutputPath);

                var idMap = new Dictionary <int, int>();
                idMap.Add(sceneTemplate.templateScene.GetInstanceID(), newSceneAsset.GetInstanceID());

                EditorSceneManager.RemapAssetReferencesInScene(newScene, refPathMap, idMap);

                EditorSceneManager.SaveScene(newScene, newSceneOutputPath);

                foreach (var clone in refMap.Values)
                {
                    if (clone)
                    {
                        EditorUtility.SetDirty(clone);
                    }
                }
                AssetDatabase.SaveAssets();
            }
            else
            {
                templatePipeline?.BeforeTemplateInstantiation(sceneTemplate, loadAdditively, newSceneOutputPath);
                newSceneTemplateInstantiating?.Invoke(sceneTemplate, newSceneOutputPath, loadAdditively);
                if (loadAdditively)
                {
                    newScene = EditorSceneManager.OpenScene(sourceScenePath, OpenSceneMode.Additive);
                }
                else
                {
                    newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
                    var sourceScene = EditorSceneManager.OpenScene(sourceScenePath, OpenSceneMode.Additive);
                    SceneManager.MergeScenes(sourceScene, newScene);
                }
            }

            SceneTemplateAnalytics.SendSceneInstantiationEvent(instantiateEvent);
            templatePipeline?.AfterTemplateInstantiation(sceneTemplate, newScene, loadAdditively, newSceneOutputPath);
            newSceneTemplateInstantiated?.Invoke(sceneTemplate, newScene, newSceneAsset, loadAdditively);

            SceneTemplateUtils.SetLastFolder(newSceneOutputPath);

            return(new System.Tuple <Scene, SceneAsset>(newScene, newSceneAsset));
        }