Esempio n. 1
0
        public static void Generate()
        {
            // Try to find an existing file in the project called "UnityConstants.cs"
            string filePath = string.Empty;

            foreach (var file in Directory.GetFiles(Application.dataPath, "*.cs", SearchOption.AllDirectories))
            {
                if (Path.GetFileNameWithoutExtension(file) == "GameAudio")
                {
                    filePath = file;
                    break;
                }
            }

            // If no such file exists already, use the save panel to get a folder in which the file will be placed.
            if (string.IsNullOrEmpty(filePath))
            {
                string directory = Application.dataPath + "/Gen/";
                filePath = Path.Combine(directory, "SoundManager.cs");
            }

            // Write out our file
            using (var writer = new StreamWriter(filePath))
            {
                writer.WriteLine("// This file is auto-generated. Modifications are not saved.");
                writer.WriteLine();
                writer.WriteLine("namespace UnitedSolution");
                writer.WriteLine("{");

                writer.WriteLine("    public partial class SoundManager");
                writer.WriteLine("    {");
                AudioClip[] Songs = Resources.LoadAll <AudioClip>("Audio/BackgroundMusic");
                foreach (var song in Songs)
                {
                    string name = song.name.MakeSafeForCode().FirstLetterToUpperCase();
                    writer.WriteLine("        public static void Play_" + name + "() {");
                    writer.WriteLine("            SoundManager.Instance.PlaySong(\"" + song.name + "\");");
                    writer.WriteLine("        }");
                }

                AudioClip[] SFXs = Resources.LoadAll <AudioClip>("Audio/EffectSounds");
                foreach (var sfx in SFXs)
                {
                    string name = sfx.name.MakeSafeForCode().FirstLetterToUpperCase();
                    writer.WriteLine("        public static void Play_" + name + "() {");
                    writer.WriteLine("            SoundManager.Instance.PlaySfx(\"" + sfx.name + "\");");
                    writer.WriteLine("        }");
                }


                writer.WriteLine("    }");
                writer.WriteLine();
                writer.WriteLine("}");
            }
            // Refresh
            AssetDatabase.Refresh();
            SyncSolution.Sync();
        }
Esempio n. 2
0
        public static void Generate()
        {
            // Try to find an existing file in the project called "UnityConstants.cs"
            string filePath = string.Empty;

            foreach (var file in Directory.GetFiles(Application.dataPath, "*.cs", SearchOption.AllDirectories))
            {
                if (Path.GetFileNameWithoutExtension(file) == "UnityConstants")
                {
                    filePath = file;
                    break;
                }
            }

            // If no such file exists already, use the save panel to get a folder in which the file will be placed.
            if (string.IsNullOrEmpty(filePath))
            {
                string directory = Application.dataPath + "/Gen/";
                filePath = Path.Combine(directory, "UnityConstants.cs");
            }

            // Write out our file
            using (var writer = new StreamWriter(filePath)) {
                writer.WriteLine("// This file is auto-generated. Modifications are not saved.");
                writer.WriteLine();
                writer.WriteLine("namespace UnitedSolution");
                writer.WriteLine("{");

                // Write out the tags
                writer.WriteLine("    public static class Tags");
                writer.WriteLine("    {");
                foreach (var tag in UnityEditorInternal.InternalEditorUtility.tags)
                {
                    writer.WriteLine("        /// <summary>");
                    writer.WriteLine("        /// Name of tag '{0}'.", tag);
                    writer.WriteLine("        /// </summary>");
                    writer.WriteLine("        public const string {0} = \"{1}\";", MakeSafeForCode(tag), tag);
                }
                writer.WriteLine("    }");
                writer.WriteLine();

                // Write out sorting layers
                writer.WriteLine("    public static class SortingLayers");
                writer.WriteLine("    {");
                foreach (var layer in SortingLayer.layers)
                {
                    writer.WriteLine("        /// <summary>");
                    writer.WriteLine("        /// ID of sorting layer '{0}'.", layer.name);
                    writer.WriteLine("        /// </summary>");
                    writer.WriteLine("        public const int {0} = {1};", MakeSafeForCode(layer.name), layer.id);
                }
                writer.WriteLine("    }");
                writer.WriteLine();

                // Write out layers
                writer.WriteLine("    public static class Layers");
                writer.WriteLine("    {");
                for (int i = 0; i < 32; i++)
                {
                    string layer = UnityEditorInternal.InternalEditorUtility.GetLayerName(i);
                    if (!string.IsNullOrEmpty(layer))
                    {
                        writer.WriteLine("        /// <summary>");
                        writer.WriteLine("        /// Index of layer '{0}'.", layer);
                        writer.WriteLine("        /// </summary>");
                        writer.WriteLine("        public const int {0} = {1};", MakeSafeForCode(layer), i);
                    }
                }
                writer.WriteLine();
                for (int i = 0; i < 32; i++)
                {
                    string layer = UnityEditorInternal.InternalEditorUtility.GetLayerName(i);
                    if (!string.IsNullOrEmpty(layer))
                    {
                        writer.WriteLine("        /// <summary>");
                        writer.WriteLine("        /// Bitmask of layer '{0}'.", layer);
                        writer.WriteLine("        /// </summary>");
                        writer.WriteLine("        public const int {0}Mask = 1 << {1};", MakeSafeForCode(layer), i);
                    }
                }
                writer.WriteLine("    }");
                writer.WriteLine();

                // Write out scenes
                writer.WriteLine("    public static class Scenes");
                writer.WriteLine("    {");
                int sceneIndex = 0;
                foreach (var scene in EditorBuildSettings.scenes)
                {
                    if (!scene.enabled)
                    {
                        continue;
                    }

                    var sceneName = Path.GetFileNameWithoutExtension(scene.path);

                    writer.WriteLine("        /// <summary>");
                    writer.WriteLine("        /// ID of scene '{0}'.", sceneName);
                    writer.WriteLine("        /// </summary>");
                    writer.WriteLine("        public const int {0} = {1};", MakeSafeForCode(sceneName), sceneIndex);

                    sceneIndex++;
                }
                writer.WriteLine("    }");
                writer.WriteLine();

                // Write out Input axes
                writer.WriteLine("    public static class Axes");
                writer.WriteLine("    {");
                var axes             = new HashSet <string>();
                var inputManagerProp = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/InputManager.asset")[0]);
                foreach (SerializedProperty axe in inputManagerProp.FindProperty("m_Axes"))
                {
                    var name         = axe.FindPropertyRelative("m_Name").stringValue;
                    var variableName = MakeSafeForCode(name);
                    if (!axes.Contains(variableName))
                    {
                        writer.WriteLine("        /// <summary>");
                        writer.WriteLine("        /// Input axis '{0}'.", name);
                        writer.WriteLine("        /// </summary>");
                        writer.WriteLine("        public const string {0} = \"{1}\";", variableName, name);
                        axes.Add(variableName);
                    }
                }
                writer.WriteLine("    }");

                // End of namespace UnityConstants
                writer.WriteLine("}");
                writer.WriteLine();
            }

            // Refresh
            AssetDatabase.Refresh();
            SyncSolution.Sync();
        }
Esempio n. 3
0
        public static void Generate()
        {
            //enable Smart Logger
            SmartLogger.Initialize(LogLevel.ALL, LogDetails.ALL);
            // If no such file exists already, use the save panel to get a folder in which the file will be placed.
            string filePath  = EditorUtility.OpenFilePanel("Select singleton to generate code", Application.dataPath, "cs");
            string className = Path.GetFileNameWithoutExtension(filePath);

            Logger.info("Run on " + filePath);
            Logger.info("Class: " + className);

            StringBuilder sourceBuilder = new StringBuilder();
            string        content       = null;

            Dictionary <string, List <string> > parameters = new Dictionary <string, List <string> >();

            using (var reader = new StreamReader(filePath))
            {
                content = reader.ReadToEnd().Replace("public class ", "public partial class ");
            }

            // save our changes
            using (var writer = new StreamWriter(filePath))
            {
                writer.Write(content);
            }

            //find out the method should be generate
            using (var reader = new StreamReader(filePath))
            {
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    int    private_method_index = line.IndexOf(PRIVATE_METHOD_NAME_PATTERN);
                    int    public_method_index  = line.IndexOf(METHOD_NAME_PATTERN);

                    int    index   = private_method_index;
                    string pattern = PRIVATE_METHOD_NAME_PATTERN;
                    if (index == -1) //switch to "public method" pattern
                    {
                        index   = public_method_index;
                        pattern = METHOD_NAME_PATTERN;
                    }

                    if (index != -1)
                    {
                        int           length          = 1 + Mathf.Abs(index + pattern.Length - line.LastIndexOf(")"));
                        string        methodName      = line.Substring(index + pattern.Length, length).Trim().FirstLetterToUpperCase();
                        List <string> temp_parameters = new List <string>();
                        Logger.info("Method definination: " + methodName);
                        if (!line.Contains("()") && !line.Contains("( )"))
                        {
                            int    startIndex  = line.IndexOf(START_PARAMETER_PATTERN);
                            int    paramLength = Mathf.Abs(startIndex + START_PARAMETER_PATTERN.Length - line.LastIndexOf(")"));
                            string parameter   = line.Substring(startIndex + START_PARAMETER_PATTERN.Length, paramLength).Trim();

                            string[] param = parameter.Split(new string[] { ", " }, StringSplitOptions.None);

                            foreach (string p in param)
                            {
                                Logger.info("Parameter Definination: " + p.ToString());
                                string[] pp = p.Trim().Split(' ');
                                if (pp.Length > 1)
                                {
                                    Logger.info("Variable name: " + pp[1].ToString());
                                    temp_parameters.Add(pp[1]);
                                }
                            }
                            parameters.Add(methodName, temp_parameters);
                        }
                        else
                        {
                            parameters.Add(methodName, temp_parameters);
                        }
                    }
                }
            }
            //write to auto-generated *.cs file
            string generatedFilePath = Application.dataPath + "/Gen/" + className + ".cs";

            using (var writer = new StreamWriter(generatedFilePath))
            {
                writer.WriteLine("// This file is auto-generated. Modifications are not saved.");
                writer.WriteLine();
                writer.WriteLine("using UnitedSolution;\n");

                writer.WriteLine("    public partial class " + className);
                writer.WriteLine("    {");
                foreach (var methodName in parameters)
                {
                    List <string> temp_parameters = methodName.Value;
                    string        parameter       = "(";
                    for (int i = 0; i < temp_parameters.Count; i++)
                    {
                        parameter += temp_parameters[i];
                        if (i != temp_parameters.Count - 1)
                        {
                            parameter += ", ";
                        }
                    }
                    parameter += ");";
                    Logger.info("parameter: " + parameter);

                    writer.WriteLine("        public static void " + methodName.Key + " {");

                    string methodParam = "_" + methodName.Key.FirstLetterToLowerCase();
                    //if(usePublicMethodPattern)
                    //{
                    //}
                    methodParam = methodParam.Substring(0, methodParam.LastIndexOf('('));
                    writer.WriteLine("            " + className + ".Instance." + methodParam + parameter);
                    writer.WriteLine("        }");
                }

                writer.WriteLine("    }");
                writer.WriteLine();
            }
            // Refresh
            AssetDatabase.ImportAsset(filePath);
            AssetDatabase.ImportAsset(generatedFilePath);
            SyncSolution.Sync();
        }