GetProjectFolder() публичный статический Метод

public static GetProjectFolder ( ) : string
Результат string
Пример #1
0
    /// <summary>
    /// Adds a project-relative TextScene to the TextScene buildsettings
    /// and the corresponding binary temp file is written to the standard
    /// Unity build settings.
    /// </summary>
    public static bool AddSceneToBuild(string scene)
    {
        string projectFolder = EditorHelper.GetProjectFolder();

        string fullScenePath = projectFolder + scene;

        //Make sure the scene file actually exists
        if (!File.Exists(fullScenePath))
        {
            EditorUtility.DisplayDialog("ERROR", "The text scene '" + scene + "' does not seem to exist!", "OK");
            return(false);
        }

        List <string> sceneList = ReadScenes();

        if (sceneList.Contains(scene))
        {
            EditorUtility.DisplayDialog("Already added", "This scene is already in the build list", "OK");
            return(false);
        }

        Debug.Log("Added scene to build: " + scene);

        sceneList.Add(scene);

        WriteBuildSettings(sceneList);

        return(true);
    }
Пример #2
0
    private void BuildNext()
    {
        //TODO: Must be fixed up to work with callback - scene saving does not work very well if done
        //      immediately after load, which is why we need to make this into a async operation
        //      of some sort. See unity case 336621.
        //Run through all scenes and build them based on the human readable representation.
        if (sceneQueue.Count > 0)
        {
            string textScene = sceneQueue.Dequeue();

            Debug.Log("Building temp for: " + textScene);

            string result = TextSceneDeserializer.Load(EditorHelper.GetProjectFolder() + textScene, this.BuildNext);

            if (result.Length == 0)
            {
                EditorUtility.DisplayDialog("Scene does not exist", "Unable to find scene file: " + textScene + " Will be excluded from build", "OK");
                BuildNext();
            }
            else
            {
                binarySceneList.Add(result);
            }
        }
        else
        {
            FinishBuild();
        }
    }
Пример #3
0
    /// <summary>
    /// Sets the current TextScene we will monitor for changes. Also stores the current
    /// scene Unity has open (the binary version) so we can detect if the user suddenly
    /// changes to either a new scene or a different binary scene without going via
    /// the TextScene functionality.
    /// </summary>
    /// <param name="filename">
    /// A <see cref="System.String"/> holding the full absolute path to the TextScene file.
    /// </param>
    public void SetCurrentScene(string filename)
    {
        alarmingEditorScene    = EditorApplication.currentScene;
        currentTempBinaryScene = EditorHelper.GetProjectFolder() + alarmingEditorScene;

        currentScene = filename;

        //Use file timestamp instead of DateTime.Now for consistency reasons.
        if (File.Exists(currentTempBinaryScene))
        {
            currentSceneLoaded = File.GetLastWriteTime(currentTempBinaryScene);
        }
        else
        {
            Debug.LogWarning("Unable to find temp file: " + currentTempBinaryScene);
            currentSceneLoaded = DateTime.Now;
        }

        Debug.Log("TextSceneMonitor setting current scene: " + filename + " (" + currentSceneLoaded + ")");

        nextCheckForChangedFile = EditorApplication.timeSinceStartup + 1.0f;

        PlayerPrefs.SetString("TextSceneMonitorCurrentScene", currentScene);
        PlayerPrefs.SetString("TextSceneAlarmingEditorScene", alarmingEditorScene);
    }
Пример #4
0
    /// <summary>
    /// Writes a list of project-relative TextScene files to buildsettings. The
    /// corresponding binary unity scenes are stored in the Unity standard
    /// build-settings.
    /// </summary>
    private static void WriteBuildSettings(List <string> sceneList)
    {
        StreamWriter writer = File.CreateText(EditorHelper.GetProjectFolder() + buildSettingsFile);

        foreach (string scene in sceneList)
        {
            writer.Write("scene " + scene + '\n');
        }

        writer.Close();

        //Also update the editor build settings
        List <EditorBuildSettingsScene> binaryScenes = new List <EditorBuildSettingsScene>();

        foreach (string scene in sceneList)
        {
            EditorBuildSettingsScene ebss = new EditorBuildSettingsScene();

            ebss.path    = TextScene.TextSceneToTempBinaryFile(scene);
            ebss.enabled = true;

            binaryScenes.Add(ebss);
        }

        EditorBuildSettings.scenes = binaryScenes.ToArray();
    }
Пример #5
0
    /// <summary>
    /// Returns the time the build settings file was last written to.
    /// </summary>
    public static DateTime BuildSettingsDate()
    {
        string fullPath = EditorHelper.GetProjectFolder() + buildSettingsFile;

        if (!File.Exists(fullPath))
        {
            return(new DateTime(1, 1, 1));
        }

        return(File.GetLastWriteTime(fullPath));
    }
Пример #6
0
    public static void SaveAs()
    {
        string currentScene = EditorApplication.currentScene;

        string startFolder = "";



        if (currentScene.Length == 0)
        {
            SaveCurrent();
            return;
        }
        else if (currentScene.StartsWith("Assets/"))
        {
            string needResaveAs = currentScene.Substring(currentScene.IndexOf('/'));

            needResaveAs = needResaveAs.Replace(".unity", ".txt");

            needResaveAs = Application.dataPath + needResaveAs;

            startFolder = needResaveAs.Substring(0, needResaveAs.LastIndexOf('/'));
        }
        else
        {
            //TODO: Verify that it starts with TempScenes?

            startFolder = EditorHelper.GetProjectFolder() + TextScene.TempToTextSceneFile(currentScene);

            startFolder = startFolder.Substring(0, startFolder.LastIndexOf('/'));
        }

        string fileName = EditorUtility.SaveFilePanel("Save TextScene as", startFolder, "textscene", "txt");

        if (fileName.Length > 0)
        {
            Save(fileName);
        }
    }
Пример #7
0
    /// <summary>
    /// Reads in the current list of scenes registered in the custom
    /// TextScene buildsettings.
    /// </summary>
    public static List <string> ReadScenes()
    {
        List <string> sceneList = new List <string>();

        string fullPath = EditorHelper.GetProjectFolder() + buildSettingsFile;

        if (!File.Exists(fullPath))
        {
            return(sceneList);
        }

        StreamReader reader = File.OpenText(fullPath);

        while (!reader.EndOfStream)
        {
            string line = reader.ReadLine();

            string[] elements = line.Trim().Split();

            string key = "";
            string val = "";

            if (elements.Length >= 2)
            {
                key = elements[0];
                val = elements[1];
            }

            if (key == "scene")
            {
                sceneList.Add(val);
            }
        }

        reader.Close();

        return(sceneList);
    }
Пример #8
0
    public override void OnInspectorGUI()
    {
        TextSceneObject tso = target as TextSceneObject;

        EditorGUILayout.BeginVertical();

        GUILayout.Label("External scene");

        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("Open scene: ");

        if (GUILayout.Button(tso.textScene.name))
        {
            if (EditorUtility.DisplayDialog("Open scenefile?", "Do you want to close the current scene and open the scene pointed to by this TextSceneObject?", "Yes", "No"))
            {
                TextSceneDeserializer.LoadSafe(EditorHelper.GetProjectFolder() + AssetDatabase.GetAssetPath(tso.textScene));
                GUIUtility.ExitGUI();
            }
        }

        EditorGUILayout.EndHorizontal();
        EditorGUILayout.EndVertical();
    }
Пример #9
0
    /// <summary>
    /// Creates a new TextSceneMonitor and reads in relevant values from PlayerPrefs (such as
    /// last monitored scene).
    /// </summary>
    public TextSceneMonitor()
    {
        process = null;

        currentScene = PlayerPrefs.GetString("TextSceneMonitorCurrentScene", "");

        alarmingEditorScene = PlayerPrefs.GetString("TextSceneAlarmingEditorScene", "");

        currentTempBinaryScene = EditorHelper.GetProjectFolder() + alarmingEditorScene;

        //Use file timestamp instead of DateTime.Now for consistency reasons.
        if (File.Exists(currentTempBinaryScene))
        {
            currentSceneLoaded = File.GetLastWriteTime(currentTempBinaryScene);
        }
        else
        {
            Debug.LogWarning("Unable to find temp file: " + currentTempBinaryScene);
            currentSceneLoaded = DateTime.Now;
        }

        Debug.Log("Creating new TextSceneMonitor instance: " + currentScene);
    }
Пример #10
0
    private void DeserializeTextScene(StreamReader stream, string name, GameObject parent)
    {
        string line = stream.ReadLine().Trim();

        char [] separators = new char [] { ' ', ',' };

        string[] parts = line.Split(separators, System.StringSplitOptions.RemoveEmptyEntries);

        string assetPath = null;

        //Expected format:
        //  assetpath Asset/Path/asset, GUID
        if (parts.Length > 1)
        {
            assetPath = parts[1].Trim();

            //Prefer GUID over path if present.
            if (parts.Length > 2)
            {
                string guid = parts[2].Trim();

                assetPath = AssetDatabase.GUIDToAssetPath(guid);
            }
        }

        if (assetPath == null)
        {
            Debug.LogError("Failed to get path for textscene object '" + name + "': " + line);
            return;
        }

        string fullPath = EditorHelper.GetProjectFolder() + assetPath;

        GameObject go = null;

        if (currentPass == Pass.CreateObjects)
        {
            //Random initial name until the local links have been set up.
            //FIXME: I can imagine this random stuff can blow up at any point when we least need it.
            //go = new GameObject(Random.Range(10000, 100000).ToString());
            go = new GameObject(name);
            go.AddComponent <TextSceneObject>().textScene = AssetDatabase.LoadAssetAtPath(assetPath, typeof(TextAsset)) as TextAsset;

            //Debug.Log("Full: " + fullPath + " recguard: " + recursionGuard);

            string fullName = "/" + name;

            if (parent != null)
            {
                fullName = Helper.GetFullName(parent) + fullName;
            }

            if (fullPath.ToLower() == recursionGuard.ToLower())
            {
                EditorUtility.DisplayDialog("Recursion guard", "Loading this TextScene (" + assetPath + ") into the current TextScene will throw you into an infinite recursion. Please remove the TextScene object (" + fullName + ") or change the TextScene it points to so it no longer results in a loop", "OK");
            }
            else
            {
                bool result = (new TextSceneDeserializer(go, recursionGuard)).LoadScene(fullPath);

                if (!result)
                {
                    Debug.LogError("Failed to load TextSceneObject: " + line);
                }
            }

            gameObjects.Enqueue(go);
        }
        else
        {
            go = gameObjects.Dequeue();
        }

        go.name = name;

        if (parent != null)
        {
            go.transform.parent = parent.transform;
        }

        DeserializeTransform(stream, go.transform);
    }
Пример #11
0
    //TODO: Finish up and make public!
    public static bool ValidateBuildSettings(out List <string> invalidScenes)
    {
        SyncBuildSettings();

        List <string> sceneList = ReadScenes();

        invalidScenes = new List <string>();

        foreach (string scene in sceneList)
        {
            string absoluteTextScene = EditorHelper.GetProjectFolder() + scene;

            //Make sure the scene exists at all in a TextScene format
            if (!File.Exists(absoluteTextScene))
            {
                Debug.LogWarning("Scene does not exist: " + scene);

                EditorApplication.isPlaying = false;

                if (EditorUtility.DisplayDialog("Invalid scene", "The scene '" + scene + "' is listed in your build settings but it does not exist. Do you want to remove it from build settings?", "Yes", "No"))
                {
                    TextScene.RemoveSceneFromBuild(scene);
                }
                else
                {
                    invalidScenes.Add(scene);
                    continue;
                }
            }
            else
            {
                //While the textscene might be present, we also need the binary temp file.
                //Make sure there is one up-to-date, if not, the user should be prompted
                //to generate one.
                string absoluteBinaryTempScene = EditorHelper.GetProjectFolder() + TextSceneToTempBinaryFile(scene);

                if (!File.Exists(absoluteBinaryTempScene))
                {
                    Debug.LogWarning("Temp scene does not exist: " + absoluteBinaryTempScene);

                    //EditorApplication.isPlaying = false;
                    //if (EditorUtility.DisplayDialog("Missing temp file", "Missing temp file for '" + scene + "' - do you want to generate it now?", "Yes", "No"))
                    //    TextSceneDeserializer.LoadSafe(absoluteTextScene);

                    invalidScenes.Add(scene);
                    continue;
                }
                else
                {
                    //Both files exist, but we also need to make sure the temp scene isn't outdated.
                    DateTime textSceneTime       = File.GetLastWriteTime(absoluteTextScene);
                    DateTime binaryTempSceneTime = File.GetLastWriteTime(absoluteBinaryTempScene);

                    if (textSceneTime > binaryTempSceneTime)
                    {
                        Debug.LogWarning("Temp scene for '" + scene + "' is outdated: " + binaryTempSceneTime + " is older than " + textSceneTime);

                        //EditorApplication.isPlaying = false;
                        //if (EditorUtility.DisplayDialog("Outdated temp file", "Outdated temp file for '" + scene + "' - do you want to update it now?", "Yes", "No"))
                        //    TextSceneDeserializer.LoadSafe(absoluteTextScene);

                        invalidScenes.Add(scene);
                        continue;
                    }
                }
            }
        }

        return(invalidScenes.Count == 0);
    }
Пример #12
0
    void OnGUI()
    {
        GUILayout.BeginVertical();

        scroll = GUILayout.BeginScrollView(scroll);

        GUILayout.Label("Scenes to build");

        foreach (string scene in scenes)
        {
            EditorGUILayout.BeginHorizontal();

            if (GUILayout.Button(scene))
            {
                TextSceneDeserializer.LoadSafe(EditorHelper.GetProjectFolder() + scene);
                GUIUtility.ExitGUI();
                return;
            }


            if (GUILayout.Button("Remove", GUILayout.MaxWidth(60)))
            {
                if (EditorUtility.DisplayDialog("Remove scene", "Are you sure you want to remove this scene from the build settings?", "Yes", "No"))
                {
                    TextScene.RemoveSceneFromBuild(scene);
                    LoadSettings();
                }
            }

            if (GUILayout.Button("+", GUILayout.MaxWidth(20)))
            {
                TextScene.MoveScenePosition(scene, 1);
                LoadSettings();
            }

            if (GUILayout.Button("-", GUILayout.MaxWidth(20)))
            {
                TextScene.MoveScenePosition(scene, -1);
                LoadSettings();
            }

            GUILayout.EndHorizontal();
        }

        if (scenes.Count > 0)
        {
            EditorGUILayout.Separator();
            EditorGUILayout.BeginVertical(GUILayout.MaxWidth(150));

            if (GUILayout.Button("Build Temp"))
            {
                TextScene.BuildTempScenes();
                GUIUtility.ExitGUI();
                return;
            }

            if (GUILayout.Button("Build Streamed Web"))
            {
                TextScene.Build(BuildTarget.WebPlayerStreamed);
                GUIUtility.ExitGUI();
                return;
            }

            if (GUILayout.Button("Build Web"))
            {
                TextScene.Build(BuildTarget.WebPlayer);
                GUIUtility.ExitGUI();
                return;
            }

            if (GUILayout.Button("Build OSX"))
            {
                TextScene.Build(BuildTarget.StandaloneOSXUniversal);
                GUIUtility.ExitGUI();
                return;
            }

            if (GUILayout.Button("Build Windows"))
            {
                TextScene.Build(BuildTarget.StandaloneWindows);
                GUIUtility.ExitGUI();
                return;
            }

            EditorGUILayout.EndVertical();
        }
        else
        {
            GUILayout.Label("Add scenes via the TextScene menu item to enable build");
        }

        EditorGUILayout.Separator();

        if (GUILayout.Button("Add current", GUILayout.MaxWidth(100)))
        {
            TextScene.AddCurrentSceneToBuild();
            LoadSettings();
        }

        EditorGUILayout.Separator();

        if (GUILayout.Button("Validate Settings", GUILayout.MaxWidth(100)))
        {
            List <string> invalidScenes;

            if (TextScene.ValidateBuildSettings(out invalidScenes))
            {
                EditorUtility.DisplayDialog("Valid settings", "The build settings seem valid enough", "OK");
            }
            else
            {
                StringBuilder sb = new StringBuilder();

                sb.Append("There were errors in validation: \n");

                foreach (string scene in invalidScenes)
                {
                    sb.Append("   ");
                    sb.Append(scene);
                    sb.Append('\n');
                }

                sb.Append("Try running 'Build Temp' to fix them up, or inspect the console for further hints.");

                EditorUtility.DisplayDialog("Validation failed", sb.ToString(), "OK");
            }
        }

        GUILayout.EndScrollView();

        GUILayout.EndVertical();
    }
Пример #13
0
    public static void SaveCurrent()
    {
        string currentScene = EditorApplication.currentScene;

        string needResaveAs = "";

        //Don't save over scenes not in the TempScenes-folder.
        if (currentScene.StartsWith("Assets/"))
        {
            if (!EditorUtility.DisplayDialog("Need resave", "This scene is residing in your Assets folder. For the TextScenes we need to re-save the .unity file in a temporary folder - you should from now on not be working on this scene file, but rather use the new TextScene file that will be generated next to your currently open scene.", "OK", "Hell no."))
            {
                return;
            }

            needResaveAs = currentScene.Substring(currentScene.IndexOf('/'));

            needResaveAs = needResaveAs.Replace(".unity", ".txt");

            needResaveAs = Application.dataPath + needResaveAs;



            if (File.Exists(needResaveAs))
            {
                string overwriteFile = currentScene.Replace(".unity", ".txt");

                Object o = AssetDatabase.LoadAssetAtPath(overwriteFile, typeof(TextAsset));

                Selection.activeObject = o;

                if (!EditorUtility.DisplayDialog("Overwrite?", "A file already exists at the default save position (" + overwriteFile + ") - do you want to overwrite, or choose a new name?", "Overwrite", "Choose new name"))
                {
                    needResaveAs = "";
                }
                else
                {
                    Debug.Log("Converting and overwriting scene to text: " + needResaveAs);
                }
            }
            else
            {
                Debug.Log("Converting scene to text: " + needResaveAs);
            }


            currentScene = "";
        }


        if (currentScene.Length == 0 || needResaveAs.Length > 0)
        {
            string startPath = Application.dataPath;

            string path = needResaveAs.Length > 0 ? needResaveAs : EditorUtility.SaveFilePanel("Save scene file", startPath, "newtextscene", "txt");

            if (path.Length == 0)
            {
                return;
            }

            currentScene = path.Replace(EditorHelper.GetProjectFolder(), "");

            Debug.LogWarning("Saving new scene to text: " + currentScene);
        }
        else
        {
            Debug.LogWarning("Re-saving temp scene to text: " + EditorApplication.currentScene);
        }


        string textScene = currentScene.Substring(currentScene.IndexOf('/'));


        string saveFile = textScene.Replace(".unity", ".txt");

        Save(Application.dataPath + saveFile);
    }
Пример #14
0
    public static void Save(string filePath)
    {
        if (EditorApplication.isPlayingOrWillChangePlaymode)
        {
            EditorUtility.DisplayDialog("Game is running", "You cannot save in Play-mode", "OK");
            return;
        }



        Transform[] sceneObjects = Helper.GetObjectsOfType <Transform>();

        List <Transform> sortedTransforms = new List <Transform>();

        //Sort these to get a somewhat predictable output
        foreach (Transform o in sceneObjects)
        {
            //Only serialize root objects, children are handled by their parents
            if (o.parent == null)
            {
                sortedTransforms.Add(o);
            }
        }

        warnings = 0;

        sortedTransforms.Sort(CompareTransform);

        StringBuilder sceneText = new StringBuilder();

        foreach (Transform o in sortedTransforms)
        {
            Serialize(sceneText, o.gameObject, 0);
        }


        //TODO: If the save didn't go without warnings, show a message/confirmation
        //      dialog here.
        if (warnings > 0)
        {
            EditorUtility.DisplayDialog("ERROR: Scene not saved", "You had " + warnings + " errors or warnings during the save. Please fix them up and try again.", "OK");
            return;
        }


        StreamWriter fileStream = File.CreateText(filePath);

        fileStream.Write(sceneText.ToString());
        fileStream.Close();

        Debug.Log("Wrote scene to file: " + filePath);

        string assetPath = filePath.Replace(EditorHelper.GetProjectFolder(), "");

        Debug.Log("Reimporting: " + assetPath);

        //Import the asset.
        AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);

        Selection.activeObject = AssetDatabase.LoadAssetAtPath(assetPath, typeof(TextAsset));

        TextSceneDeserializer.Load(filePath);
    }
Пример #15
0
    public Status Update()
    {
        if (saveAndReload.Length == 0)
        {
            Debug.LogError("Invalid saveandreload name! Cancelling load/save process...");
            return(Status.Failed);
        }

        if (saveAndReloadTimer > 0)
        {
            EditorUtility.DisplayProgressBar("Creating temp...", "Creating binary temp file for TextScene: " + state.ToString(), 1.0f - saveAndReloadTimer / SAVE_AND_RELOAD_FRAMES);

            saveAndReloadTimer--;
            return(Status.Working);
        }
        else
        {
            if (state == State.SaveTemp)
            {
                Debug.Log("SaveAndReload: " + saveAndReload);

                ///FIXME: Unity sometimes puts a lock on the scenes we try to save, this is a CRUEL way to
                ///get around it.
                ///
                ///Repro-steps: *Comment out the try/catch
                ///             *Clean out tempscenes-folder.
                ///             *Open up a scene (LEVEL1) from build settings, hit play
                ///             *While playing, do something to make the game
                ///              change to another level (LEVEL2).
                ///             *Stop playing, you should now be back in the level where you
                ///              hit play from.
                ///             *Try to switch to the level you switched to in-game (LEVEL2).
                ///             *You should, after the progress bar has completed, be prompted
                ///              with an error saying Unity could not move file from Temp/Tempfile
                ///
                try
                {
                    FileStream f = File.OpenWrite(saveAndReload);
                    f.Close();
                }
                catch
                {
                    Debug.LogWarning("HACK: Getting around 'access denied' on temp files!");

                    //HACK: This seems to make Unity release the file so we can try to save it in a new go.
                    if (!EditorApplication.OpenScene(saveAndReload))
                    {
                        //Uh oh.
                        Debug.LogError("HACK failed! What to do next?");
                        EditorUtility.ClearProgressBar();
                        return(Status.Failed);
                    }

                    TextSceneDeserializer.Load(EditorHelper.GetProjectFolder() + TextScene.TempToTextSceneFile(EditorApplication.currentScene), saveAndReloadCallback);
                    return(Status.Working);
                }

                if (!EditorApplication.SaveScene(saveAndReload))
                {
                    Debug.LogError("Failed to save temp: " + saveAndReload);


                    if (EditorUtility.DisplayDialog("ERROR", "Failed to save temp (" + saveAndReload + ") - try again?", "Yes", "No"))
                    {
                        saveAndReloadTimer = Mathf.RoundToInt(SAVE_AND_RELOAD_FRAMES);
                    }
                    else
                    {
                        return(Status.Failed);
                    }


                    EditorUtility.ClearProgressBar();
                    return(Status.Working);
                }

                state = State.CreateNew;
                saveAndReloadTimer = Mathf.RoundToInt(SAVE_AND_RELOAD_FRAMES);
                return(Status.Working);
            }
            else if (state == State.CreateNew)
            {
                EditorApplication.NewScene();

                state = State.LoadTemp;
                saveAndReloadTimer = Mathf.RoundToInt(SAVE_AND_RELOAD_FRAMES);
                return(Status.Working);
            }
            else if (state == State.LoadTemp)
            {
                if (!EditorApplication.OpenScene(saveAndReload))
                {
                    Debug.LogError("Failed to load temp: " + saveAndReload);

                    if (EditorUtility.DisplayDialog("ERROR", "Failed to load temp (" + saveAndReload + ") - try again?", "Yes", "No"))
                    {
                        saveAndReloadTimer = Mathf.RoundToInt(SAVE_AND_RELOAD_FRAMES);
                    }
                    else
                    {
                        return(Status.Failed);
                    }

                    EditorUtility.ClearProgressBar();
                    return(Status.Working);
                }

                string writtenFile = EditorHelper.GetProjectFolder() + EditorApplication.currentScene;

                DateTime writtenTime = File.GetLastWriteTime(writtenFile);

                Debug.Log("Wrote temp file at " + writtenTime);

                TextSceneMonitor.Instance.SetCurrentScene(EditorHelper.GetProjectFolder() + TextScene.TempToTextSceneFile(EditorApplication.currentScene));

                saveAndReload = "";

                EditorUtility.ClearProgressBar();

                return(Status.Complete);
            }
        }

        Debug.LogError("Failing....");
        return(Status.Failed);
    }