public void ClassCleanup()
 {
     EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);
 }
Ejemplo n.º 2
0
    private void CreateScene()
    {
        AssetDatabase.SaveAssets();

        Type.GetType("UnityEditor.LogEntries,UnityEditor.dll")
        .GetMethod("Clear", BindingFlags.Static | BindingFlags.Public)
        .Invoke(null, null);



        newScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Additive);
        EditorSceneManager.CloseScene(EditorSceneManager.GetSceneAt(0), true);

        newScene.name = folderName;

        //GameObject canvasRoot = new GameObject("CanvasRoot");
        CreateEventSystem();
        GameObject rootObj = CreateCanvas();

        menuRoot = rootObj.AddComponent <MenuRoot>();

        //menuRoot.allMenus = new Dictionary<string, MenuManager>();

        int    tempI         = 0;
        string tempFolder    = "";
        string tempFolderA   = "";
        string tempFolderDel = "";

        while (tempI < 1000)
        {
            tempFolder = "assets/" + TEMP_DIR + tempI.ToString();
            if (!Directory.Exists(tempFolder))
            {
                tempFolderDel = tempFolder;
                tempFolderA   = tempFolder + "/Resources";
                Directory.CreateDirectory(tempFolderA);
                break;
            }
            else
            {
                tempI++;
            }
        }

        tempFolderA += "/" + TEMP_SUB_DIR;

        FileUtil.CopyFileOrDirectory(sceneDirectory, tempFolderA);
        //FileUtil.CopyFileOrDirectoryFollowSymlinks(sceneDirectory, tempFolderA);
        AssetDatabase.Refresh();

        MenuData[] menus = Resources.LoadAll <MenuData>(TEMP_SUB_DIR);
        tempMenus   = new Dictionary <string, MenuManager>();
        tempButtons = new Dictionary <Button, UiData>();

        tempUis = new Queue <KeyValuePair <Transform, List <UiSortData> > >();

        foreach (MenuData md in menus)
        {
            MenuManager menu = (MenuManager)CreateMenu(md, rootObj.transform);
            menuRoot.AddMenu(menu);
            tempMenus.Add(md.name, menu);
        }

        foreach (KeyValuePair <Button, UiData> bb in tempButtons)
        {
            Type[] arguments = new Type[1];
            arguments[0] = typeof(int);
            MethodInfo        method = UnityEventBase.GetValidMethodInfo(menuRoot, "ShowMenu", arguments);
            UnityAction <int> ua     = Delegate.CreateDelegate(typeof(UnityAction <int>), menuRoot, method) as UnityAction <int>;

            if (bb.Value.action == ButtonAction.ShowMenu)
            {
                Debug.Log(menuRoot.allMenus.IndexOf(tempMenus[bb.Value.goTo.name]));
                int index = menuRoot.allMenus.IndexOf(tempMenus[bb.Value.goTo.name]);
                UnityEventTools.AddIntPersistentListener(bb.Key.onClick, ua, index);
            }
        }

        while (tempUis.Count > 0)
        {
            KeyValuePair <Transform, List <UiSortData> > tempK = tempUis.Dequeue();
            List <UiSortData> tempList = tempK.Value;
            for (int i = 0; i < tempList.Count; i++)
            {
                //Debug.Log("^^^: " + tempList[i].layer);
                tempList[i].ui.SetAsFirstSibling();
            }
        }

        EditorSceneManager.SaveScene(UnityEngine.SceneManagement.SceneManager.GetSceneAt(0), sceneDirectory + "/" + folderName + ".unity");

        FileUtil.DeleteFileOrDirectory(tempFolderDel);

        AssetDatabase.Refresh();

        if (myWindow != null)
        {
            myWindow.Close();
        }



        return;

        Debug.Log(":: " + sceneDirectory + ", " + folderName);

        // You can either filter files to get only neccessary files by its file extension using LINQ.
        // It excludes .meta files from all the gathers file list.
        IEnumerable <string> assetFiles = GetFiles(GetSelectedPathOrFallback()).Where(str => str.Contains(".meta") == false);

        foreach (string f in assetFiles)
        {
            Debug.Log("Files: " + f);
        }
    }
Ejemplo n.º 3
0
        // Appends to collectedAssets
        static void ExportToToolkit_Environment(
            Environment environment,
            string targetDirectory,
            HashSet <string> collectedAssets)
        {
            // make an environment
            var name     = environment.name;
            var settings = environment.m_RenderSettings;

            EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);

            var prefab = AssetDatabase.LoadAssetAtPath <GameObject>(
                "Assets/Resources/" + settings.m_EnvironmentPrefab + ".prefab");

            PrefabUtility.InstantiatePrefab(prefab);

            RenderSettings.ambientSkyColor       = settings.m_AmbientColor;
            RenderSettings.fogColor              = settings.m_FogColor;
            RenderSettings.reflectionIntensity   = settings.m_ReflectionIntensity;
            RenderSettings.defaultReflectionMode = UnityEngine.Rendering.DefaultReflectionMode.Custom;

            RenderSettings.fog              = settings.m_FogEnabled;
            RenderSettings.fogMode          = settings.m_FogMode;
            RenderSettings.fogDensity       = settings.m_FogDensity;
            RenderSettings.fogStartDistance = settings.m_FogStartDistance;
            RenderSettings.fogEndDistance   = settings.m_FogEndDistance;

            // Lights
            Object.DestroyImmediate(Object.FindObjectOfType <Light>());
            for (int li = 0; li < environment.m_Lights.Count; li++)
            {
                var lsettings = environment.m_Lights[li];
                var light     = new GameObject("Light " + li, typeof(Light)).GetComponent <Light>();
                light.transform.position = lsettings.m_Position;
                light.transform.rotation = lsettings.m_Rotation;
                light.color     = lsettings.Color;
                light.type      = lsettings.m_Type;
                light.range     = lsettings.m_Range;
                light.spotAngle = lsettings.m_SpotAngle;
                light.intensity = 1.0f;
                light.shadows   = lsettings.m_ShadowsEnabled ? LightShadows.Hard : LightShadows.None;
            }

            // Camera
            var cam = Object.FindObjectOfType <Camera>();

            cam.transform.position = new Vector3(0, 15, 0);
            cam.nearClipPlane      = 0.5f;
            cam.farClipPlane       = 10000.0f;
            cam.fieldOfView        = 60;
            cam.clearFlags         = CameraClearFlags.Skybox;
            cam.backgroundColor    = settings.m_ClearColor;


            RenderSettings.customReflection = settings.m_ReflectionCubemap;
            if (settings.m_SkyboxCubemap)
            {
                Error("These guid shenanigans don't work yet: {0}", name);
                Material skyboxMaterialTmp  = new Material(Shader.Find("Custom/Skybox"));
                Guid     skyboxMaterialGuid = GuidUtils.Uuid5(environment.m_Guid, "skyboxMaterial");
                Material skyboxMaterial     = CreateAssetWithGuid_Incorrect(
                    skyboxMaterialTmp, name + "_Skybox.mat", skyboxMaterialGuid);
                string sbAssetPath = AssetDatabase.GetAssetPath(skyboxMaterial);

                collectedAssets.UnionWith(GetDependencies(sbAssetPath, includeRoot: false));

                string sbFinalPath = targetDirectory + "/" + sbAssetPath;
                CopyAsset(sbAssetPath, sbFinalPath);

                RenderSettings.skybox = skyboxMaterial;
                RenderSettings.skybox.SetColor("_Tint", settings.m_SkyboxTint);
                RenderSettings.skybox.SetFloat("_Exposure", settings.m_SkyboxExposure);
                RenderSettings.skybox.SetTexture("_Tex", settings.m_SkyboxCubemap);
            }
            else
            {
                RenderSettings.skybox = null;
            }

            Lightmapping.realtimeGI = false;
            Lightmapping.bakedGI    = false;

            // Store scene
            var sceneAssetPath = "Assets/Dynamic/" + name + ".unity";
            var sceneFinalPath = targetDirectory + "/Environments/" + Path.GetFileName(sceneAssetPath);

            EditorSceneManager.SaveScene(SceneManager.GetActiveScene(), sceneAssetPath);
            AssetDatabase.ImportAsset(sceneAssetPath, ImportAssetOptions.ForceSynchronousImport);

            CopyAsset(sceneAssetPath, sceneFinalPath);
            collectedAssets.UnionWith(GetDependencies(sceneAssetPath, includeRoot: false));
            SetFileGuid_Incorrect(sceneFinalPath, environment.m_Guid);

            AssetDatabase.DeleteAsset(sceneAssetPath);

            EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects);
        }
Ejemplo n.º 4
0
        void CreateSubFolders(string rootPath)
        {
            DirectoryInfo rootinfo    = null;
            List <string> folderNames = new List <string>();

            // Creating Directory for Art
            rootinfo = Directory.CreateDirectory(rootPath + "/Art");
            if (rootinfo.Exists)
            {
                folderNames.Clear();
                folderNames.Add("Animation");
                folderNames.Add("Audio");
                folderNames.Add("Objects/Models");
                folderNames.Add("Materials");
                folderNames.Add("Prefabs");
                folderNames.Add("Textures");

                CreateFolders(rootPath + "/Art", folderNames);
            }


            // Creating Directory for Code
            rootinfo = Directory.CreateDirectory(rootPath + "/Code");
            if (rootinfo.Exists)
            {
                folderNames.Clear();
                folderNames.Add("Editor");
                folderNames.Add("Scripts");
                folderNames.Add("Shaders");
                CreateFolders(rootPath + "/Code", folderNames);
            }
            // Creating Directory for Resoruces
            rootinfo = Directory.CreateDirectory(rootPath + "/Resoruces");
            if (rootinfo.Exists)
            {
                folderNames.Clear();
                folderNames.Add("Characters");
                folderNames.Add("Managers");
                folderNames.Add("Props");
                folderNames.Add("UI");

                CreateFolders(rootPath + "/Resoruces", folderNames);
            }
            // Creating Directory for Prefabs
            rootinfo = Directory.CreateDirectory(rootPath + "/Prefabs");
            if (rootinfo.Exists)
            {
                folderNames.Clear();
                folderNames.Add("Characters");
                folderNames.Add("Props");
                folderNames.Add("UI");

                CreateFolders(rootPath + "/Prefabs", folderNames);
            }

            // Create Scenes
            DirectoryInfo sceneInfo = Directory.CreateDirectory(rootPath + "/Scenes");

            if (sceneInfo.Exists)
            {
                // Create base level scenes needed for a simple game
                Scene currentFrontendScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
                EditorSceneManager.SaveScene(currentFrontendScene, "Assets/" + gameName + "/Scenes/" + gameName + "_Frontend.unity", true);

                Scene currentMainScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
                EditorSceneManager.SaveScene(currentMainScene, "Assets/" + gameName + "/Scenes/" + gameName + "_Main.unity", true);

                Scene currentStartupScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
                EditorSceneManager.SaveScene(currentStartupScene, "Assets/" + gameName + "/Scenes/" + gameName + "_Startup.unity", true);
            }
            DirectoryInfo devSceneInfo = Directory.CreateDirectory(rootPath + "/Scenes/Development");

            if (devSceneInfo.Exists)
            {
                // Create base level scenes needed for a simple game
                Scene currentDevelopmentScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
                EditorSceneManager.SaveScene(currentDevelopmentScene, "Assets/" + gameName + "/Scenes/Development/" + gameName + "_Development.unity", true);
            }
        }
        /// <summary>
        /// Creates a new scene into which we'll load the block.
        /// </summary>
        /// <returns></returns>
        private static Scene CreateSceneForBlock()
        {
            var newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive);

            return(newScene);
        }
Ejemplo n.º 6
0
 public static void NewEmptyScene()
 {
     EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);
 }
Ejemplo n.º 7
0
        internal void SwitchToEditMode()
        {
            this.m_EditMode = AvatarEditor.EditMode.Starting;
            this.ChangeInspectorLock(true);
            this.sceneSetup = EditorSceneManager.GetSceneManagerSetup();
            EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects).name = "Avatar Configuration";
            this.m_GameObject = UnityEngine.Object.Instantiate <GameObject>(this.prefab);
            if (base.serializedObject.FindProperty("m_OptimizeGameObjects").boolValue)
            {
                AnimatorUtility.DeoptimizeTransformHierarchy(this.m_GameObject);
            }
            Animator component = this.m_GameObject.GetComponent <Animator>();

            if (component != null && component.runtimeAnimatorController == null)
            {
                AnimatorController animatorController = new AnimatorController();
                animatorController.hideFlags = HideFlags.DontSave;
                animatorController.AddLayer("preview");
                animatorController.layers[0].stateMachine.hideFlags = HideFlags.DontSave;
                component.runtimeAnimatorController = animatorController;
            }
            Dictionary <Transform, bool> modelBones = AvatarSetupTool.GetModelBones(this.m_GameObject.transform, true, null);

            AvatarSetupTool.BoneWrapper[] humanBones = AvatarSetupTool.GetHumanBones(base.serializedObject, modelBones);
            this.m_ModelBones      = AvatarSetupTool.GetModelBones(this.m_GameObject.transform, false, humanBones);
            Selection.activeObject = this.m_GameObject;
            UnityEngine.Object[] array = Resources.FindObjectsOfTypeAll(typeof(SceneHierarchyWindow));
            for (int i = 0; i < array.Length; i++)
            {
                SceneHierarchyWindow sceneHierarchyWindow = (SceneHierarchyWindow)array[i];
                sceneHierarchyWindow.SetExpandedRecursive(this.m_GameObject.GetInstanceID(), true);
            }
            this.CreateEditor();
            this.m_EditMode    = AvatarEditor.EditMode.Editing;
            this.m_SceneStates = new List <AvatarEditor.SceneStateCache>();
            IEnumerator enumerator = SceneView.sceneViews.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    SceneView sceneView = (SceneView)enumerator.Current;
                    this.m_SceneStates.Add(new AvatarEditor.SceneStateCache
                    {
                        state = new SceneView.SceneViewState(sceneView.m_SceneViewState),
                        view  = sceneView
                    });
                    sceneView.m_SceneViewState.showFlares         = false;
                    sceneView.m_SceneViewState.showMaterialUpdate = false;
                    sceneView.m_SceneViewState.showFog            = false;
                    sceneView.m_SceneViewState.showSkybox         = false;
                    sceneView.m_SceneViewState.showImageEffects   = false;
                    sceneView.FrameSelected();
                }
            }
            finally
            {
                IDisposable disposable;
                if ((disposable = (enumerator as IDisposable)) != null)
                {
                    disposable.Dispose();
                }
            }
        }
    private void OnGUI()
    {
        #region ScrollView
        scrollPosition = GUILayout.BeginScrollView(scrollPosition);
        GUILayout.Space(space);

        if (GUILayout.Button("Create new level", GUILayout.Height(buttonHeight), GUILayout.Width(buttonWidth)))
        {
            newSceneIndex = FindAppropriateIndex();

            if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
            {
                // Create new scene
                EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);

                // Add new scene to build settings
                AddNewSceneToBuildSetting(newSceneIndex);

                // Add prefabs to new scene
                AddPrefabsToNewScene();

                // Add background to new scene
                AddBackgroundToNewScene();

                // Save scene after adding everything
                SaveScene();
            }
            return;
        }

        GUILayout.Space(space);

        GUILayout.BeginHorizontal();
        GUILayout.Label("Frame type", GUILayout.Width(labelWidth));
        // Popup (it's a dropdown)
        popupIndex = EditorGUILayout.Popup(popupIndex, levelEditorSO.frameType, GUILayout.Height(dropdownHeight), GUILayout.Width(dropdownWidth));
        GUILayout.EndHorizontal();

        GUILayout.Space(space);

        GUILayout.BeginHorizontal();
        GUILayout.Label("Scene Folder", GUILayout.Width(labelWidth));
        GUI.SetNextControlName("dropdownFolderName");
        folderIndex = EditorGUILayout.Popup(folderIndex, levelEditorSO.sceneFolderName, GUILayout.Height(dropdownHeight), GUILayout.Width(dropdownWidth));
        GUILayout.EndHorizontal();

        GUI.enabled = true;

        #region Edit existing level


        #region Textfield && Arrows
        EditorGUILayout.BeginHorizontal();
        GUIStyle gUIStyleButton = new GUIStyle(GUI.skin.button);
        gUIStyleButton.fontSize = 20;

        // Left arrow
        if (GUILayout.Button("↤", gUIStyleButton, GUILayout.Height(buttonHeight), GUILayout.Width(50)))
        {
            int newNumber = (int.Parse(textFieldNumber) - 1);
            if (newNumber >= 1)
            {
                textFieldNumber = newNumber.ToString();
                //ShowYesNoPopup();
                ChangeImage();
                GUI.FocusControl("dropdownFolderName");
            }
        }

        // Textfield
        GUIStyle gUIStyle = new GUIStyle(GUI.skin.textField);
        gUIStyle.alignment = TextAnchor.MiddleLeft;
        textFieldNumber    = EditorGUILayout.TextField(textFieldNumber, gUIStyle, GUILayout.Height(buttonHeight), GUILayout.Width(100));

        // Right arrow
        if (GUILayout.Button("↦", gUIStyleButton, GUILayout.Height(buttonHeight), GUILayout.Width(50)))
        {
            int newNumber = (int.Parse(textFieldNumber) + 1);
            textFieldNumber = newNumber.ToString();
            //ShowYesNoPopup();
            ChangeImage();
            GUI.FocusControl("dropdownFolderName");
        }
        EditorGUILayout.EndHorizontal();
        #endregion

        GUILayout.Space(space / 2);


        if (GUILayout.Button($"Open Level {textFieldNumber}", GUILayout.Height(buttonHeight), GUILayout.Width(buttonWidth)))
        {
            if (int.TryParse(textFieldNumber, out int i))
            {
                ShowUnSavePopup();
                ChangeImage();
            }
        }
        deleteScene = EditorGUILayout.BeginToggleGroup("Delete current scene", deleteScene);
        GUILayout.Space(space / 2);
        if (GUILayout.Button("Delete", GUILayout.Height(buttonHeight), GUILayout.Width(buttonWidth)))
        {
            string sceneName = EditorSceneManager.GetActiveScene().name;
            string filePath  = $"Assets/_Main/_Scenes/{levelEditorSO.sceneFolderName[folderIndex]}/{sceneName}.unity";
            if (File.Exists(filePath))
            {
                if (EditorUtility.DisplayDialog($"Delete Level{textFieldNumber} scene", $"Do you want to delete {sceneName} scene?", "Yes", "No"))
                {
                    File.Delete(filePath);
#if UNITY_EDITOR
                    AssetDatabase.Refresh();
                    UpdateSceneAmountInScriptableObject(false);
#endif

                    EditorBuildSettingsScene[] originalSettingScenes = EditorBuildSettings.scenes;
                    EditorBuildSettingsScene   sceneToRemove         = new EditorBuildSettingsScene($"Assets/_Main/_Scenes/{levelEditorSO.sceneFolderName[folderIndex]}/{sceneName}.unity", true);
                    EditorBuildSettingsScene[] newSettings           = new EditorBuildSettingsScene[originalSettingScenes.Length - 1];
                    for (int i = 0, j = 0; i < originalSettingScenes.Length; i++)
                    {
                        if (originalSettingScenes[i].path != sceneToRemove.path)
                        {
                            newSettings[j++] = originalSettingScenes[i];
                        }
                    }
                    EditorBuildSettings.scenes = newSettings;

                    EditorSceneManager.OpenScene(EditorBuildSettings.scenes[EditorBuildSettings.scenes.Length - 1].path);

                    EditorUtility.DisplayDialog("Message", $"{sceneName} has been deleted from project folder and build settings", "OK");
                }
            }
            else
            {
                EditorUtility.DisplayDialog("File not found", $"Can not find IntroScene in folder {filePath}", "OK");
            }
        }
        EditorGUILayout.EndToggleGroup();
        #endregion

        #region Intro, Menu, Menu Select Scene
        int minus = 30;
        GUILayout.Space(space);
        GUILayout.BeginHorizontal();
        if (GUILayout.Button($"Open {levelEditorSO.sceneFolderName[folderIndex]} Select Level", GUILayout.Width(buttonWidth - minus), GUILayout.Height(buttonHeight)))
        {
            if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
            {
                try
                {
                    EditorSceneManager.OpenScene($"Assets/_Main/_Scenes/{levelEditorSO.sceneFolderName[folderIndex]}/MenuSelectLevel{folderIndex + 1}.unity");
                }
                catch (Exception)
                {
                    EditorUtility.DisplayDialog("File not found", $"Can not find MenuSelectLevel{folderIndex + 1} in folder Assets/_Main/_Scenes/{levelEditorSO.sceneFolderName[folderIndex]}", "OK");
                }
            }
        }

        if (GUILayout.Button("Open Intro Scene", GUILayout.Width(buttonWidth - minus), GUILayout.Height(buttonHeight)))
        {
            if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
            {
                try
                {
                    EditorSceneManager.OpenScene("Assets/_Main/_Scenes/IntroScene.unity");
                }
                catch (Exception)
                {
                    EditorUtility.DisplayDialog("File not found", "Can not find IntroScene in folder Assets/_Main/_Scenes/", "OK");
                }
            }
        }
        GUILayout.EndHorizontal();

        GUILayout.Space(space);
        GUILayout.BeginHorizontal();
        if (GUILayout.Button("Open Menu Scene", GUILayout.Width(buttonWidth - minus), GUILayout.Height(buttonHeight)))
        {
            if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
            {
                try
                {
                    EditorSceneManager.OpenScene("Assets/_Main/_Scenes/MenuScene.unity");
                }
                catch (Exception)
                {
                    EditorUtility.DisplayDialog("File not found", "Can not find MenuScene in folder Assets/_Main/_Scenes/", "OK");
                }
            }
        }

        if (GUILayout.Button("Open Menu Select Episode", GUILayout.Width(buttonWidth - minus), GUILayout.Height(buttonHeight)))
        {
            if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
            {
                try
                {
                    EditorSceneManager.OpenScene("Assets/_Main/_Scenes/MenuSelectEpisode.unity");
                }
                catch (Exception)
                {
                    EditorUtility.DisplayDialog("File not found", "Can not find MenuSelectEpisode in folder Assets/_Main/_Scenes/", "OK");
                }
            }
        }
        GUILayout.EndHorizontal();
        #endregion

        #region Scene Image
        GUI.enabled = true;
        GUILayout.Space(space / 2);
        if (!imageExist)
        {
            GUILayout.Label("Image does not exists in folder");
        }
        else
        {
            GUILayout.Label(imageOfLevel, GUILayout.Width(Screen.width - 25));
        }
        #endregion

        GUILayout.EndScrollView();
        #endregion end ScrollView
    }
        public void SetupScenes()
        {
            // first check if the scene is already open
            if (EditorSceneManager.sceneCount > 1)
            {
                // multiple scenes are open, check if the second one is an extendedUI scene
                if (EditorSceneManager.GetSceneAt(1).name.Contains(ProWorkstationManager.extendedUIString))
                {
                    Debug.Log("extendedUI scene open already");
                    return;
                }
                // multiple scenes are open, but not extended UI scene
                Debug.Log("secondary scene is open, but is not an extendedUI scene. please close extra scenes and try again.");
                return;
            }
            else
            {
                // if only one scene is open
                var activeScene = EditorSceneManager.GetActiveScene();
                EditorSceneManager.SaveOpenScenes();
                Debug.Log("active scene saved!");

                // first see if this scene is already the extended UI scene
                string secondSceneName = "";
                string newPath         = "";
                if (activeScene.name.Contains(ProWorkstationManager.extendedUIString))
                {
                    // if the active scene is already open, try to load the regular scene
                    secondSceneName = activeScene.name.Substring(0, activeScene.name.IndexOf(ProWorkstationManager.extendedUIString));
                    newPath         = activeScene.path;
                    newPath         = newPath.Substring(0, newPath.LastIndexOf(ProWorkstationManager.extendedUIString)) + ".unity";
                    Debug.Log(secondSceneName);
                    Debug.Log(newPath);
                }
                else
                {
                    // try to load _extendedUI version of that scene instead
                    secondSceneName = activeScene.name + ProWorkstationManager.extendedUIString;
                    newPath         = activeScene.path;
                    newPath         = newPath.Insert(newPath.LastIndexOf(".unity"), ProWorkstationManager.extendedUIString);
                }

                bool loadedSceneSuccessfully = TryLoadingScene(newPath);
                if (loadedSceneSuccessfully)
                {
                    Debug.Log("found existing complementary scene, loading");
                }
                else
                {
                    // if it doesn't exist, create and save it
                    Scene extendedScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive);
                    extendedScene.name = secondSceneName;
                    EditorSceneManager.SaveScene(extendedScene, newPath);
                    Debug.Log("didn't find existing complementary scene, creating it");
                }

                // set active scene to lkg one, just to fix lighting
                Scene lkgScene = EditorSceneManager.GetActiveScene();
                for (int i = 0; i < EditorSceneManager.sceneCount; i++)
                {
                    if (!EditorSceneManager.GetSceneAt(i).name.Contains(ProWorkstationManager.extendedUIString))
                    {
                        lkgScene = EditorSceneManager.GetSceneAt(i);
                    }
                }
                EditorSceneManager.SetActiveScene(lkgScene);
            }
        }
Ejemplo n.º 10
0
        internal void SwitchToAssetMode(bool selectAvatarAsset)
        {
            foreach (var state in m_SceneStates)
            {
                if (state.view == null)
                {
                    continue;
                }

                state.view.sceneViewState.showFog             = state.state.showFog;
                state.view.sceneViewState.showFlares          = state.state.showFlares;
                state.view.sceneViewState.showMaterialUpdate  = state.state.showMaterialUpdate;
                state.view.sceneViewState.showSkybox          = state.state.showSkybox;
                state.view.sceneViewState.showImageEffects    = state.state.showImageEffects;
                state.view.sceneViewState.showParticleSystems = state.state.showParticleSystems;
            }

            m_EditMode = EditMode.Stopping;

            DestroyEditor();

            ChangeInspectorLock(m_InspectorLocked);

            // if the user started play mode While in Edit mode it not clear what we should do
            // for now let the active scene open and do nothing
            if (!EditorApplication.isPlaying)
            {
                EditorApplication.CallbackFunction CleanUpSceneOnDestroy = null;
                CleanUpSceneOnDestroy = () =>
                {
                    string currentScene = SceneManager.GetActiveScene().path;
                    if (currentScene.Length > 0)
                    {
                        // in this case the user did save manually the current scene and want to keep it or
                        // he did open a new scene
                        // do nothing
                    }
                    // Restore scene that was loaded when user pressed Configure button
                    else if (sceneSetup != null && sceneSetup.Length > 0)
                    {
                        EditorSceneManager.RestoreSceneManagerSetup(sceneSetup);
                        sceneSetup = null;
                    }
                    else
                    {
                        EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects);
                    }

                    // Make sure that we restore the "original" selection if we exit Avatar Editing mode
                    // from the avatar tooling itself (e.g by clicking done).
                    if (selectAvatarAsset)
                    {
                        SelectAsset();
                    }

                    if (!m_CameFromImportSettings)
                    {
                        m_EditMode = EditMode.NotEditing;
                    }

                    EditorApplication.update -= CleanUpSceneOnDestroy;
                };

                EditorApplication.update += CleanUpSceneOnDestroy;
            }

            // Reset back the Edit Mode specific states (they probably should be better encapsulated)
            m_GameObject = null;
            m_ModelBones = null;
        }
Ejemplo n.º 11
0
        public static void OpenEmptyScene()
        {
#if UNITY_EDITOR
            EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
#endif
        }
Ejemplo n.º 12
0
        internal void SwitchToEditMode()
        {
            // Ensure we show the main stage before starting editing the Avatar since it will be edited on the Main stage (we are using a main scene for it)
            if (StageNavigationManager.instance.currentItem.isPrefabStage)
            {
                StageNavigationManager.instance.GoToMainStage(false, StageNavigationManager.Analytics.ChangeType.GoToMainViaAvatarSetup);
            }

            m_EditMode = EditMode.Starting;

            // Lock inspector
            ChangeInspectorLock(true);

            // Store current setup in hierarchy
            sceneSetup = EditorSceneManager.GetSceneManagerSetup();

            // Load temp scene
            Scene scene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects);

            scene.name = "Avatar Configuration";

            // Instantiate character
            m_GameObject = Instantiate(prefab) as GameObject;
            if (serializedAssetImporter.FindProperty("m_OptimizeGameObjects").boolValue)
            {
                AnimatorUtility.DeoptimizeTransformHierarchy(m_GameObject);
            }

            SerializedProperty humanBoneArray = serializedAssetImporter.FindProperty("m_HumanDescription.m_Human");

            // First get all available modelBones
            Dictionary <Transform, bool> modelBones = AvatarSetupTool.GetModelBones(m_GameObject.transform, true, null);

            AvatarSetupTool.BoneWrapper[] humanBones = AvatarSetupTool.GetHumanBones(humanBoneArray, modelBones);

            m_ModelBones = AvatarSetupTool.GetModelBones(m_GameObject.transform, false, humanBones);

            Selection.activeObject = m_GameObject;

            // Unfold all nodes in hierarchy
            // TODO@MECANIM: Only expand actual bones
            foreach (SceneHierarchyWindow shw in Resources.FindObjectsOfTypeAll(typeof(SceneHierarchyWindow)))
            {
                shw.SetExpandedRecursive(m_GameObject.GetInstanceID(), true);
            }
            CreateEditor();

            m_EditMode = EditMode.Editing;

            // Frame in scene view
            m_SceneStates = new List <SceneStateCache>();
            foreach (SceneView s in SceneView.sceneViews)
            {
                m_SceneStates.Add(new SceneStateCache {
                    state = new SceneView.SceneViewState(s.sceneViewState), view = s
                });
                s.sceneViewState.showFlares          = false;
                s.sceneViewState.showMaterialUpdate  = false;
                s.sceneViewState.showFog             = false;
                s.sceneViewState.showSkybox          = false;
                s.sceneViewState.showImageEffects    = false;
                s.sceneViewState.showParticleSystems = false;
                s.FrameSelected();
            }
        }
Ejemplo n.º 13
0
        internal static InstantiationResult Instantiate(SceneTemplateAsset sceneTemplate, bool loadAdditively, string newSceneOutputPath, SceneTemplateAnalytics.SceneInstantiationType instantiationType)
        {
            if (!sceneTemplate.isValid)
            {
                throw new Exception("templateScene is empty");
            }

            if (EditorApplication.isUpdating)
            {
                Debug.LogFormat(LogType.Warning, LogOption.None, null, "Cannot instantiate a new scene while updating the editor is disallowed.");
                return(null);
            }

            // If we are loading additively, we cannot add a new Untitled scene if another unsaved Untitled scene is already opened
            if (loadAdditively && SceneTemplateUtils.HasSceneUntitled())
            {
                Debug.LogFormat(LogType.Warning, LogOption.None, null, "Cannot instantiate a new scene additively while an unsaved Untitled scene already exists.");
                return(null);
            }

            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.hasCloneableDependencies;

            SceneAsset newSceneAsset = null;
            Scene      newScene;

            var templatePipeline = sceneTemplate.CreatePipeline();

            if (hasAnyCloneableDependencies || loadAdditively)
            {
                if (!InstantiateInMemoryScene(sceneTemplate, sourceScenePath, ref newSceneOutputPath, out var rootFolder, out var isTempMemory))
                {
                    instantiateEvent.isCancelled = true;
                    SceneTemplateAnalytics.SendSceneInstantiationEvent(instantiateEvent);
                    return(null);
                }

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

                newSceneAsset = AssetDatabase.LoadAssetAtPath <SceneAsset>(newSceneOutputPath);

                var refPathMap = new Dictionary <string, string>();
                var idMap      = new Dictionary <int, int>();
                if (hasAnyCloneableDependencies)
                {
                    var refMap = CopyCloneableDependencies(sceneTemplate, newSceneOutputPath, ref refPathMap);
                    idMap.Add(sceneTemplate.templateScene.GetInstanceID(), newSceneAsset.GetInstanceID());
                    ReferenceUtils.RemapAssetReferences(refPathMap, idMap);

                    foreach (var clone in refMap.Values)
                    {
                        if (clone)
                        {
                            EditorUtility.SetDirty(clone);
                        }
                    }
                    AssetDatabase.SaveAssets();
                }

                newScene = EditorSceneManager.OpenScene(newSceneOutputPath, loadAdditively ? OpenSceneMode.Additive : OpenSceneMode.Single);

                if (hasAnyCloneableDependencies)
                {
                    EditorSceneManager.RemapAssetReferencesInScene(newScene, refPathMap, idMap);
                }

                EditorSceneManager.SaveScene(newScene, newSceneOutputPath);

                if (isTempMemory)
                {
                    newSceneAsset = null;
                    newScene.SetPathAndGuid("", newScene.guid);
                    s_CurrentInMemorySceneState.guid       = newScene.guid;
                    s_CurrentInMemorySceneState.rootFolder = rootFolder;
                    s_CurrentInMemorySceneState.hasCloneableDependencies = hasAnyCloneableDependencies;
                    s_CurrentInMemorySceneState.dependencyFolderName     = Path.GetFileNameWithoutExtension(newSceneOutputPath);
                }
            }
            else
            {
                var needTempSceneCleanup = false;
                if (SceneTemplateUtils.IsAssetReadOnly(sourceScenePath))
                {
                    sourceScenePath      = CopyToTemporaryScene(sourceScenePath);
                    needTempSceneCleanup = true;
                }

                templatePipeline?.BeforeTemplateInstantiation(sceneTemplate, loadAdditively, newSceneOutputPath);
                newSceneTemplateInstantiating?.Invoke(sceneTemplate, newSceneOutputPath, loadAdditively);
                newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
                var sourceScene = EditorSceneManager.OpenScene(sourceScenePath, OpenSceneMode.Additive);
                SceneManager.MergeScenes(sourceScene, newScene);

                if (!string.IsNullOrEmpty(newSceneOutputPath))
                {
                    EditorSceneManager.SaveScene(newScene, newSceneOutputPath);
                }

                if (needTempSceneCleanup)
                {
                    SceneTemplateUtils.DeleteAsset(sourceScenePath);
                }
            }

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

            SceneTemplateUtils.SetLastFolder(newSceneOutputPath);

            return(new InstantiationResult(newScene, newSceneAsset));
        }
        /// <summary>
        /// Generates a scene
        /// </summary>
        /// <param name="path">Where the scene is going to be stored</param>
        /// <param name="name">Name of the scene</param>
        private void CreateScene(string path, string name)
        {
            Scene currentScene = EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);

            EditorSceneManager.SaveScene(currentScene, path + "/" + name + ".unity", true);
        }
Ejemplo n.º 15
0
 public void Setup()
 {
     EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);
 }
Ejemplo n.º 16
0
    public override void OnInspectorGUI()
    {
        GUILayout.Label("relativeAssetPath:" + RelativeAssetPath());
        if (GUILayout.Button("Create Scene"))
        {
            //SceneManager
            newScene = EditorSceneManager.NewScene(
                NewSceneSetup.EmptyScene,
                NewSceneMode.Additive);

            mainScene = EditorSceneManager.GetActiveScene();
            EditorSceneManager.SetActiveScene(this.newScene);

            GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        }

        if (GUILayout.Button("Save Scene"))
        {
            string absolutepath = Application.dataPath;
            string relativepath = "Assets" + absolutepath.Substring(Application.dataPath.Length);



            EditorSceneManager.SaveScene(
                newScene,
                relativepath + "/newScene" + sceneCount++ + ".unity");

            EditorSceneManager.SetActiveScene(this.mainScene);
        }


        if (GUILayout.Button("Generate Grid"))
        {
            for (int x = 0; x < 3; x++)
            {
                for (int z = 0; z < 3; z++)
                {
                    mainScene = EditorSceneManager.GetActiveScene();

                    newScene = EditorSceneManager.NewScene(
                        NewSceneSetup.EmptyScene,
                        NewSceneMode.Additive);

                    EditorSceneManager.SetActiveScene(this.newScene);

                    GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                    cube.transform.position = new Vector3(x, 0f, z);

                    string absolutePath = Application.dataPath;
                    string relativePath = "Assets" + absolutePath.Substring(Application.dataPath.Length);


                    EditorSceneManager.SaveScene(
                        newScene,
                        relativePath + "/Scene_" + x + "_" + z + ".unity");

                    EditorSceneManager.SetActiveScene(this.mainScene);
                    EditorSceneManager.CloseScene(this.newScene, true);
                }
            }
        }


        if (GUILayout.Button("Load Grid"))
        {
            for (int x = 0; x < 3; x++)
            {
                for (int z = 0; z < 3; z++)
                {
                    string relativePath =
                        "Assets" + Application.dataPath.Substring(Application.dataPath.Length) +
                        "/Scene_" + x + "_" + z + ".unity";

                    Scene sceneToLoad = EditorSceneManager.OpenScene(relativePath, OpenSceneMode.Additive);
                }
            }
        }

        if (GUILayout.Button(("Merge Scenes to New")))
        {
            this.MergeScenesToNew();
        }


        if (GUILayout.Button("Generate, transfer, load Scenes"))
        {
            Stopwatch sw = new Stopwatch();

            for (int x = 0; x < 3; x++)
            {
                for (int z = 0; z < 3; z++)
                {
                    sw.Start();

                    // Aktuelle Szene als MainScene merken
                    mainScene = EditorSceneManager.GetActiveScene();

                    // Neue (leere) Szene erstellen
                    newScene = EditorSceneManager.NewScene(
                        NewSceneSetup.EmptyScene,
                        NewSceneMode.Additive);

                    // Neue Szene als aktive Szene setzen
                    EditorSceneManager.SetActiveScene(this.newScene);

                    //###########################
                    // Erzeuge Content:
                    GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                    cube.transform.position = new Vector3(x, 0f, z);
                    //###########################

                    // Szene speichern
                    string filename = RelativeAssetPathTo("Scene_" + x + "_" + z + ".unity");
                    EditorSceneManager.SaveScene(newScene, filename);

                    // ByteArray für Message aus Szene erstellen
                    byte[] bytes = SceneFileToByteArray(this.newScene);

                    // Filename must be send in some form...
                    //
                    //      |
                    //      |
                    // Transfer via RabbitMQ-Message
                    //      |
                    //     \|/
                    //      v

                    Scene transferedScene = ByteArrayToScene(filename, bytes);
                    EditorSceneManager.SetActiveScene(transferedScene);
                    EditorSceneManager.CloseScene(this.newScene, true);
                    sw.Stop();
                    Debug.Log("Szene " + x + "," + z + " took: " + sw.ElapsedMilliseconds + "ms");
                }
            }
        }
    }
Ejemplo n.º 17
0
 void OpenEditorScene()
 {
     EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo();
     EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects);
 }
Ejemplo n.º 18
0
        private static void ExportPackageImpl()
        {
            DisplayProgressBar("Preparing for export...", 0f);

            // Disable auto recompile.
            var wasAutoRefreshEnabled = EditorPrefs.GetBool(autoRefreshKey);

            EditorPrefs.SetBool(autoRefreshKey, false);

            // Load a temp scene and unload assets to prevent reference errors.
            sceneSetup = EditorSceneManager.GetSceneManagerSetup();
            EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);
            EditorUtility.UnloadUnusedAssetsImmediate(true);

            DisplayProgressBar("Pre-processing assets...", 0f);
            var processors = GetProcessors();

            foreach (var proc in processors)
            {
                proc.OnPackagePreProcess();
            }

            var assetPaths     = AssetDatabase.GetAllAssetPaths().Where(p => p.StartsWith(AssetsPath));
            var ignoredPaths   = assetPaths.Where(p => IsAssetIgnored(p));
            var unignoredPaths = assetPaths.Where(p => !IsAssetIgnored(p));

            // Temporary hide ignored assets.
            DisplayProgressBar("Hiding ignored assets...", .1f);
            if (IsAnyPathsIgnored)
            {
                foreach (var path in ignoredPaths)
                {
                    File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
                }
                AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
            }

            // Add license file.
            var needToAddLicense = File.Exists(LicenseFilePath);

            if (needToAddLicense)
            {
                File.Copy(LicenseFilePath, LicenseAssetPath);
                AssetDatabase.ImportAsset(LicenseAssetPath, ImportAssetOptions.ForceSynchronousImport);
            }

            // Modify scripts (namespace and copyright).
            DisplayProgressBar("Modifying scripts...", .25f);
            modifiedScripts.Clear();
            var needToModify = !string.IsNullOrEmpty(Copyright);

            if (needToModify)
            {
                foreach (var path in unignoredPaths)
                {
                    if (!path.EndsWith(".cs") && !path.EndsWith(".shader") && !path.EndsWith(".cginc"))
                    {
                        continue;
                    }

                    var fullpath           = Application.dataPath.Replace("Assets", string.Empty) + path;
                    var originalScriptText = File.ReadAllText(fullpath, Encoding.UTF8);

                    string scriptText       = string.Empty;
                    var    isImportedScript = path.Contains("ThirdParty");

                    var copyright = isImportedScript || string.IsNullOrEmpty(Copyright) ? string.Empty : "// " + Copyright;
                    if (!string.IsNullOrEmpty(copyright) && !isImportedScript)
                    {
                        scriptText += copyright + "\r\n\r\n";
                    }

                    scriptText += originalScriptText;

                    File.WriteAllText(fullpath, scriptText, Encoding.UTF8);

                    modifiedScripts.Add(fullpath, originalScriptText);
                }
            }

            // Export the package.
            DisplayProgressBar("Writing package file...", .5f);
            AssetDatabase.ExportPackage(AssetsPath, OutputPath + "/" + OutputFileName + ".unitypackage", ExportPackageOptions.Recurse);

            // Restore modified scripts.
            DisplayProgressBar("Restoring modified scripts...", .75f);
            if (needToModify)
            {
                foreach (var modifiedScript in modifiedScripts)
                {
                    File.WriteAllText(modifiedScript.Key, modifiedScript.Value, Encoding.UTF8);
                }
            }

            // Remove previously added license asset.
            if (needToAddLicense)
            {
                AssetDatabase.DeleteAsset(LicenseAssetPath);
            }

            // Un-hide ignored assets.
            DisplayProgressBar("Un-hiding ignored assets...", .95f);
            if (IsAnyPathsIgnored)
            {
                foreach (var path in ignoredPaths)
                {
                    File.SetAttributes(path, File.GetAttributes(path) & ~FileAttributes.Hidden);
                }
                AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);
            }

            DisplayProgressBar("Post-processing assets...", 1f);
            foreach (var proc in processors)
            {
                proc.OnPackagePostProcess();
            }

            EditorPrefs.SetBool(autoRefreshKey, wasAutoRefreshEnabled);
            EditorSceneManager.RestoreSceneManagerSetup(sceneSetup);

            EditorUtility.ClearProgressBar();
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Initiate the Library change process.
        /// </summary>
        /// <param name="newLib"></param>
        public static bool ChangeLibraries(NetworkLibrary newLib)
        {
            // Don't do anything if the adapters already are correct
            if (newLib == MasterNetAdapter.NetworkLibrary && newLib == NSTNetAdapter.NetLibrary)
            {
                return(true);
            }

            if (newLib == NetworkLibrary.PUN && !PUN_Exists)
            {
                Debug.LogError("Photon PUN does not appear to be installed (Cannot find the PhotonNetwork assembly). Be sure it is installed from the asset store for this project.");
                return(false);
            }

            if (newLib == NetworkLibrary.PUN2 && !PUN2_Exists)
            {
                Debug.LogError("Photon PUN2 does not appear to be installed (Cannot find the PhotonNetwork assembly). Be sure it is installed from the asset store for this project.");
                return(false);
            }

            if (!EditorUtility.DisplayDialog("Change Network Library To " + System.Enum.GetName(typeof(NetworkLibrary), newLib) + "?",
                                             "Changing libraries is a very messy brute force operation (you may see compile errors and may need to restart Unity). " +
                                             "Did you really want to do this, or are you just poking at things to see what they do?", "Change Library", "Cancel"))
            {
                return(false);
            }

            Debug.Log("Removing current adapters from game objects for Network Library change ...");
            PurgeLibraryReferences();

            // Close and reopen the current scene to remove the bugginess of orphaned scripts.
            var curscene     = EditorSceneManager.GetActiveScene();
            var curscenepath = curscene.path;

            if (EditorUtility.DisplayDialog("Save Scene Before Reload?",
                                            "Scene must be reloaded to complete the purging of old library adapters. Would you like to save this scene?", "Save Scene", "Don't Save"))
            {
                EditorSceneManager.SaveScene(curscene);
            }

            // force a scene close to eliminate weirdness
            EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);

            if (MasterNetAdapter.NetworkLibrary != newLib)
            {
                CopyUncompiledAdapters(newLib);
            }

            EditorUtility.DisplayDialog("Touch Nothing!",
                                        "Wait for the compiling animation in the bottom right of Unity to stop before doing anything. Touching NST related assets will result in broken scripts and errors.", "I Won't Touch, Promise.");


            // Flag the need for a deep global find of NSTs and NSTMasters in need of adapters
            DebugX.LogWarning("Add dependencies pending. Clicking on any NST related object in a scene " +
                              "will trigger the final steps of the transition to " + newLib + ". You may need to select the " +
                              "Player Prefab in the scene or asset folder in order to make it the default player object.", true, true);

            NetLibrarySettings.Single.dependenciesNeedToBeCheckedEverywhere = true;

            AssetDatabase.Refresh();
            EditorUtility.SetDirty(NetLibrarySettings.single);
            AssetDatabase.SaveAssets();

            return(true);
        }
Ejemplo n.º 20
0
        private bool ProcessScenes()
        {
            var scenePaths =
                AssetDatabase.FindAssets("t:Scene")
                .Select(n => AssetDatabase.GUIDToAssetPath(n))
                .ToList();

            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.Count; i++)
                {
                    var scenePath = scenePaths[i];

                    if (EditorUtility.DisplayCancelableProgressBar("Scanning Scenes", "Scene " + (i + 1) + "/" + scenePaths.Count + " - " + scenePath, (float)i / scenePaths.Count))
                    {
                        return(false);
                    }

                    EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);

                    var sceneGOs = UnityEngine.Object.FindObjectsOfType <GameObject>();

                    foreach (var go in sceneGOs)
                    {
                        if ((go.hideFlags & HideFlags.DontSaveInBuild) == 0)
                        {
                            foreach (var component in go.GetComponents <ISerializationCallbackReceiver>())
                            {
                                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);
                                }
                            }
                        }
                    }
                }

                // Load a new empty scene that will be unloaded immediately, just to be sure we completely clear all changes made by the scan
                EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single);
            }
            finally
            {
                try
                {
                    EditorUtility.DisplayProgressBar("Restoring scene setup", "", 0.5f);
                    EditorSceneManager.RestoreSceneManagerSetup(oldSceneSetup);
                }
                finally
                {
                    EditorUtility.ClearProgressBar();
                }
            }

            return(true);
        }
Ejemplo n.º 21
0
 internal void SwitchToAssetMode()
 {
     foreach (AvatarEditor.SceneStateCache current in this.m_SceneStates)
     {
         if (!(current.view == null))
         {
             current.view.m_SceneViewState.showFog            = current.state.showFog;
             current.view.m_SceneViewState.showFlares         = current.state.showFlares;
             current.view.m_SceneViewState.showMaterialUpdate = current.state.showMaterialUpdate;
             current.view.m_SceneViewState.showSkybox         = current.state.showSkybox;
             current.view.m_SceneViewState.showImageEffects   = current.state.showImageEffects;
         }
     }
     this.m_EditMode = AvatarEditor.EditMode.Stopping;
     this.DestroyEditor();
     this.ChangeInspectorLock(this.m_InspectorLocked);
     if (!EditorApplication.isUpdating && !Unsupported.IsDestroyScriptableObject(this))
     {
         string path = SceneManager.GetActiveScene().path;
         if (path.Length <= 0)
         {
             if (this.sceneSetup != null && this.sceneSetup.Length > 0)
             {
                 EditorSceneManager.RestoreSceneManagerSetup(this.sceneSetup);
                 this.sceneSetup = null;
             }
             else
             {
                 EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects);
             }
         }
     }
     else if (Unsupported.IsDestroyScriptableObject(this))
     {
         EditorApplication.CallbackFunction CleanUpSceneOnDestroy = null;
         CleanUpSceneOnDestroy = delegate
         {
             string path2 = SceneManager.GetActiveScene().path;
             if (path2.Length <= 0)
             {
                 if (this.sceneSetup != null && this.sceneSetup.Length > 0)
                 {
                     EditorSceneManager.RestoreSceneManagerSetup(this.sceneSetup);
                     this.sceneSetup = null;
                 }
                 else
                 {
                     EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects);
                 }
             }
             EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Remove(EditorApplication.update, CleanUpSceneOnDestroy);
         };
         EditorApplication.update = (EditorApplication.CallbackFunction)Delegate.Combine(EditorApplication.update, CleanUpSceneOnDestroy);
     }
     this.m_GameObject = null;
     this.m_ModelBones = null;
     this.SelectAsset();
     if (!this.m_CameFromImportSettings)
     {
         this.m_EditMode = AvatarEditor.EditMode.NotEditing;
     }
 }
Ejemplo n.º 22
0
        private void CreateUIScene()
        {
            // Create UI scene

            Scene previouslyActiveScene = SceneManager.GetActiveScene();

            newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive);
            EditorSceneManager.SaveScene(newScene, "Assets/" + Constants.GameName.NameOfGame + "/Scenes/UI/" + newSceneName + ".unity");

            // Create UI scene camera

            GameObject sceneCamera = new GameObject("" + newSceneName + "Camera");

            sceneCamera.AddComponent <Camera>();
            Camera newCamera = sceneCamera.GetComponent <Camera>();

            newCamera.clearFlags          = CameraClearFlags.Depth;
            newCamera.cullingMask         = (1 << LayerMask.NameToLayer("UI"));
            newCamera.orthographic        = true;
            newCamera.orthographicSize    = 20;
            newCamera.nearClipPlane       = 0.3f;
            newCamera.farClipPlane        = 100;
            newCamera.depth               = 1;
            newCamera.useOcclusionCulling = false;
            newCamera.allowHDR            = false;
            newCamera.allowMSAA           = false;

            // Create UI scene canvas

            GameObject sceneCanvas = new GameObject("MainCanvas");

            sceneCanvas.layer = 5; // UI layer
            sceneCanvas.AddComponent <Canvas>();
            Canvas newCanvas = sceneCanvas.GetComponent <Canvas>();

            newCanvas.renderMode    = RenderMode.ScreenSpaceCamera;
            newCanvas.worldCamera   = newCamera;
            newCanvas.planeDistance = 10;

            sceneCanvas.AddComponent <CanvasScaler>();
            CanvasScaler cc = sceneCanvas.GetComponent <CanvasScaler>();

            cc.uiScaleMode         = CanvasScaler.ScaleMode.ScaleWithScreenSize;
            cc.referenceResolution = new Vector2(750, 1334);
            cc.screenMatchMode     = CanvasScaler.ScreenMatchMode.MatchWidthOrHeight;
            cc.matchWidthOrHeight  = 0;

            sceneCanvas.AddComponent <GraphicRaycaster>();
            GraphicRaycaster gr = sceneCanvas.GetComponent <GraphicRaycaster>();

            // Create background image

            GameObject canvasBGImageObject = new GameObject("BackgroundImage");

            canvasBGImageObject.AddComponent <Image>();
            Image image = canvasBGImageObject.GetComponent <Image>();

            image.color = new Color32(255, 255, 255, 50);

            canvasBGImageObject.transform.parent = sceneCanvas.transform;
            canvasBGImageObject.AddComponent <RectTransform>();
            RectTransform rt = canvasBGImageObject.GetComponent <RectTransform>();

            rt.anchorMin          = new Vector2(0, 0);
            rt.anchorMax          = new Vector2(1, 1);
            rt.pivot              = new Vector2(0.5f, 0.5f);
            rt.localScale         = new Vector3(1, 1, 1);
            rt.anchoredPosition3D = new Vector3(0, 0, 0);
            rt.offsetMax          = rt.offsetMin = rt.anchoredPosition = new Vector2(0, 0);

            // Create UI scene activator object

            GameObject sceneActivator = new GameObject("" + newSceneName + "Activator");

            string copyPath = "Assets/" + Constants.GameName.NameOfGame + "/Scripts/ScenesLogic/" + sceneActivator.name + ".cs";

            if (File.Exists(copyPath) == false)
            { // do not overwrite
                using (StreamWriter outfile =
                           new StreamWriter(copyPath))
                {
                    outfile.WriteLine("using System.Collections;");
                    outfile.WriteLine("using System.Collections.Generic;");
                    outfile.WriteLine("using UnityEngine;");
                    outfile.WriteLine("using Peak." + Constants.GameName.NameOfGame + ".Scripts.Common;");
                    outfile.WriteLine("using Peak." + Constants.GameName.NameOfGame + ".Scripts.Autogenerated;");
                    outfile.WriteLine("");
                    outfile.WriteLine("namespace Peak." + Constants.GameName.NameOfGame + ".Scripts.ScenesLogic");
                    outfile.WriteLine("{");
                    outfile.WriteLine("    public class " + sceneActivator.name + " : SceneActivationBehaviour<" + sceneActivator.name + "> ");
                    outfile.WriteLine("    {");
                    outfile.WriteLine("        public override void Initialize()");
                    outfile.WriteLine("        {");
                    outfile.WriteLine("            base.Initialize();");
                    outfile.WriteLine("        }");
                    outfile.WriteLine("");
                    outfile.WriteLine("        public override void Show(bool animated = false)");
                    outfile.WriteLine("        {");
                    outfile.WriteLine("            base.Show(animated);");
                    outfile.WriteLine("        }");
                    outfile.WriteLine("");
                    outfile.WriteLine("        public override void Hide()");
                    outfile.WriteLine("        {");
                    outfile.WriteLine("            base.Hide();");
                    outfile.WriteLine("        }");
                    outfile.WriteLine("");
                    outfile.WriteLine("        //public override void SetButtonsEnabled(bool isEnabled)");
                    outfile.WriteLine("        //{");
                    outfile.WriteLine("            //base.SetButtonsEnabled(isEnabled);");
                    outfile.WriteLine("        //}");
                    outfile.WriteLine("    }");
                    outfile.WriteLine("}");
                }

                AssetDatabase.Refresh();
            }

            SceneManager.SetActiveScene(previouslyActiveScene);
        }
Ejemplo n.º 23
0
 public static void NewScene()
 {
     EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects);
 }
Ejemplo n.º 24
0
        private void CreateGameScene()
        {
            // Create game scene

            Scene previouslyActiveScene = SceneManager.GetActiveScene();

            newScene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Additive);
            EditorSceneManager.SaveScene(newScene, "Assets/" + Constants.GameName.NameOfGame + "/Scenes/Game/" + newSceneName + ".unity");

            // Create game scene camera

            GameObject sceneCamera = new GameObject("" + newSceneName + "Camera");

            sceneCamera.AddComponent <Camera>();
            Camera newCamera = sceneCamera.GetComponent <Camera>();

            newCamera.clearFlags          = CameraClearFlags.Depth;
            newCamera.cullingMask         = -1;
            newCamera.orthographic        = true;
            newCamera.orthographicSize    = 20;
            newCamera.nearClipPlane       = 0.3f;
            newCamera.farClipPlane        = 100;
            newCamera.depth               = 1;
            newCamera.useOcclusionCulling = true;
            newCamera.allowHDR            = false;
            newCamera.allowMSAA           = true;

            // Create game scene light

            GameObject sceneLight = new GameObject("" + newSceneName + "Light");

            sceneLight.AddComponent <Light>();
            Light newLight = sceneLight.GetComponent <Light>();

            newLight.type    = LightType.Directional;
            newLight.shadows = LightShadows.None;

            // Create game scene activator object

            GameObject sceneActivator = new GameObject("" + newSceneName + "Activator");

            string copyPath = "Assets/" + Constants.GameName.NameOfGame + "/Scripts/ScenesLogic/" + sceneActivator.name + ".cs";

            if (File.Exists(copyPath) == false)
            { // do not overwrite
                using (StreamWriter outfile =
                           new StreamWriter(copyPath))
                {
                    outfile.WriteLine("using System.Collections;");
                    outfile.WriteLine("using System.Collections.Generic;");
                    outfile.WriteLine("using UnityEngine;");
                    outfile.WriteLine("using Peak." + Constants.GameName.NameOfGame + ".Scripts.Common;");
                    outfile.WriteLine("using Peak." + Constants.GameName.NameOfGame + ".Scripts.Autogenerated;");
                    outfile.WriteLine("");
                    outfile.WriteLine("namespace Peak." + Constants.GameName.NameOfGame + ".Scripts.ScenesLogic");
                    outfile.WriteLine("{");
                    outfile.WriteLine("    public class " + sceneActivator.name + " : SceneActivationBehaviour<" + sceneActivator.name + "> ");
                    outfile.WriteLine("    {");
                    outfile.WriteLine("        [SerializeField]");
                    outfile.WriteLine("        public Light[] sceneLights;");
                    outfile.WriteLine("");
                    outfile.WriteLine("        [SerializeField]");
                    outfile.WriteLine("        public GameObject featureRoot;");
                    outfile.WriteLine("");
                    outfile.WriteLine("        public override void Initialize()");
                    outfile.WriteLine("        {");
                    outfile.WriteLine("            base.Initialize();");
                    outfile.WriteLine("        }");
                    outfile.WriteLine("");
                    outfile.WriteLine("        public override void Show(bool animated = false)");
                    outfile.WriteLine("        {");
                    outfile.WriteLine("            base.Show(animated);");
                    outfile.WriteLine("        }");
                    outfile.WriteLine("");
                    outfile.WriteLine("        public override void Hide()");
                    outfile.WriteLine("        {");
                    outfile.WriteLine("            base.Hide();");
                    outfile.WriteLine("        }");
                    outfile.WriteLine("");
                    outfile.WriteLine("        //public override void SetButtonsEnabled(bool isEnabled)");
                    outfile.WriteLine("        //{");
                    outfile.WriteLine("            //base.SetButtonsEnabled(isEnabled);");
                    outfile.WriteLine("        //}");
                    outfile.WriteLine("    }");
                    outfile.WriteLine("}");
                }

                AssetDatabase.Refresh();
            }

            SceneManager.SetActiveScene(previouslyActiveScene);
        }
Ejemplo n.º 25
0
 public void ResetScence()
 {
     EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);
 }
        public void SetUpOnce()
        {
            var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);

            SceneManager.SetActiveScene(scene);
        }
Ejemplo n.º 27
0
        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);
                        }

                        var openScene = EditorSceneManager.OpenScene(scenePath, OpenSceneMode.Single);

                        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;
            }
        }
 public void TearDownOnce()
 {
     EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);
 }
 private static void CleanupScene()
 {
     EditorSceneManager.NewScene(NewSceneSetup.DefaultGameObjects, NewSceneMode.Single);
 }
        public void ClassInit()
        {
            var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);

            SceneManager.SetActiveScene(scene);
        }