private void CreateUIPanelCode(GameObject uiPrefab, string uiPrefabPath, PanelCodeInfo panelCodeInfo)
        {
            if (null == uiPrefab)
            {
                return;
            }

            var behaviourName = uiPrefab.name;

            var strFilePath = CodeGenUtil.GenSourceFilePathFromPrefabPath(uiPrefabPath, behaviourName);

            if (mScriptKitInfo.IsNotNull())
            {
                if (File.Exists(strFilePath) == false)
                {
                    if (mScriptKitInfo.Templates.IsNotNull() && mScriptKitInfo.Templates[0].IsNotNull())
                    {
                        mScriptKitInfo.Templates[0].Generate(strFilePath, behaviourName, UIKitSettingData.GetProjectNamespace(), null);
                    }
                }
            }
            else
            {
                if (File.Exists(strFilePath) == false)
                {
                    UIPanelTemplate.Write(behaviourName, strFilePath, UIKitSettingData.Load().Namespace, UIKitSettingData.Load());
                }
            }

            CreateUIPanelDesignerCode(behaviourName, strFilePath, panelCodeInfo);
            Debug.Log(">>>>>>>Success Create UIPrefab Code: " + behaviourName);
        }
        public static void Write(string name, string scriptsFolder, string scriptNamespace, PanelCodeInfo panelCodeInfo,
                                 UIKitSettingData uiKitSettingData)
        {
            var scriptFile = scriptsFolder + "/{0}.Designer.cs".FillFormat(name);
            var writer     = File.CreateText(scriptFile);

            writer.WriteLine("// Generate Id:{0}".FillFormat(Guid.NewGuid().ToString()));
            writer.WriteLine("using UnityEngine;");
            writer.WriteLine();

            if (uiKitSettingData.IsDefaultNamespace)
            {
                writer.WriteLine("// 1.请在菜单 编辑器扩展/Namespace Settings 里设置命名空间");
                writer.WriteLine("// 2.命名空间更改后,生成代码之后,需要把逻辑代码文件(非 Designer)的命名空间手动更改");
            }

            writer.WriteLine("namespace {0}".FillFormat(scriptNamespace.IsTrimNullOrEmpty()
                ? uiKitSettingData.Namespace
                : scriptNamespace));
            writer.WriteLine("{");
            writer.WriteLine("\tpublic partial class {0}".FillFormat(name));
            writer.WriteLine("\t{");

            foreach (var bindInfo in panelCodeInfo.BindInfos)
            {
                writer.WriteLine("\t\tpublic {0} {1};".FillFormat(bindInfo.BindScript.ComponentName, bindInfo.Name));
            }

            writer.WriteLine();
            writer.WriteLine("\t}");
            writer.WriteLine("}");

            writer.Close();
        }
Example #3
0
        private void CreateUIPanelDesignerCode(string behaviourName, string uiUIPanelfilePath)
        {
            var dir = uiUIPanelfilePath.Replace(behaviourName + ".cs", "");
            var generateFilePath = dir + behaviourName + ".Designer.cs";

            RegisteredTemplateGeneratorsFactory.RegisterTemplate <PanelCodeData, UIPanelDesignerTemplate>();

            var factory = new RegisteredTemplateGeneratorsFactory();

            var generators = factory.CreateGenerators(new UIGraph(), UIMarkCollector.mPanelCodeData);

            CompilingSystem.GenerateFile(new FileInfo(generateFilePath), new CodeFileGenerator(UIKitSettingData.GetProjectNamespace())
            {
                Generators = generators.ToArray()
            });

            RegisteredTemplateGeneratorsFactory.UnRegisterTemplate <PanelCodeData>();

            foreach (var elementCodeData in UIMarkCollector.mPanelCodeData.ElementCodeDatas)
            {
                var elementDir = string.Empty;
                elementDir = elementCodeData.MarkedObjInfo.MarkObj.GetUIMarkType() == UIMarkType.Element
                                        ? (dir + behaviourName + "/").CreateDirIfNotExists()
                                        : (Application.dataPath + "/" + UIKitSettingData.GetScriptsPath() + "/Components/").CreateDirIfNotExists();
                CreateUIElementCode(elementDir, elementCodeData);
            }
        }
Example #4
0
        public static void Write(string name, string scriptsFolder, UIKitSettingData uiKitSettingData)
        {
            var scriptFile = scriptsFolder + "/{0}.cs".FillFormat(name);

            if (File.Exists(scriptFile))
            {
                return;
            }

            var writer = File.CreateText(scriptFile);

            writer.WriteLine("using UnityEngine;");
            writer.WriteLine("using QFramework;");
            writer.WriteLine();

            if (uiKitSettingData.IsDefaultNamespace)
            {
                writer.WriteLine("// 1.请在菜单 编辑器扩展/Namespace Settings 里设置命名空间");
                writer.WriteLine("// 2.命名空间更改后,生成代码之后,需要把逻辑代码文件(非 Designer)的命名空间手动更改");
            }

            writer.WriteLine("namespace {0}".FillFormat(uiKitSettingData.Namespace));
            writer.WriteLine("{");
            writer.WriteLine("\tpublic partial class {0} : ViewController".FillFormat(name));
            writer.WriteLine("\t{");
            writer.WriteLine("\t\tvoid Start()");
            writer.WriteLine("\t\t{");
            writer.WriteLine("\t\t\t// Code Here");
            writer.WriteLine("\t\t}");
            writer.WriteLine("\t}");
            writer.WriteLine("}");
            writer.Close();
        }
Example #5
0
        public static string GenSourceFilePathFromPrefabPath(string uiPrefabPath, string prefabName)
        {
            var strFilePath = String.Empty;

            var prefabDirPattern = UIKitSettingData.Load().UIPrefabDir;

            if (uiPrefabPath.Contains(prefabDirPattern))
            {
                strFilePath = uiPrefabPath.Replace(prefabDirPattern, UIKitSettingData.GetScriptsPath());
            }
            else if (uiPrefabPath.Contains("/Resources"))
            {
                strFilePath = uiPrefabPath.Replace("/Resources", UIKitSettingData.GetScriptsPath());
            }
            else
            {
                strFilePath = uiPrefabPath.Replace("/" + CodeGenUtil.GetLastDirName(uiPrefabPath), UIKitSettingData.GetScriptsPath());
            }

            strFilePath.Replace(prefabName + ".prefab", string.Empty).CreateDirIfNotExists();

            strFilePath = strFilePath.Replace(".prefab", ".cs");

            return(strFilePath);
        }
Example #6
0
        private void OnEnable()
        {
            mRootLayout = new VerticalLayout();

            new ButtonView(LocaleText.Generate,
                           () => { CreateViewControllerCode.DoCreateCodeFromScene((target as ViewController).gameObject); })
            .Height(30)
            .AddTo(mRootLayout);

            if (mCodeGenerateInfo.ScriptsFolder.IsNullOrEmpty())
            {
                var setting = UIKitSettingData.Load();
                mCodeGenerateInfo.ScriptsFolder = "Assets" + setting.DefaultViewControllerScriptDir;
            }

            if (mCodeGenerateInfo.PrefabFolder.IsNullOrEmpty())
            {
                var setting = UIKitSettingData.Load();
                mCodeGenerateInfo.PrefabFolder = "Assets" + setting.DefaultViewControllerPrefabDir;
            }

            if (mCodeGenerateInfo.ScriptName.IsNullOrEmpty())
            {
                mCodeGenerateInfo.ScriptName = mCodeGenerateInfo.name;
            }

            if (mCodeGenerateInfo.Namespace.IsNullOrEmpty())
            {
                var setting = UIKitSettingData.Load();
                mCodeGenerateInfo.Namespace = setting.Namespace;
            }
        }
        private void CreateUIPanelDesignerCode(string behaviourName, string uiUIPanelfilePath, PanelCodeInfo panelCodeInfo)
        {
            var dir = uiUIPanelfilePath.Replace(behaviourName + ".cs", "");
            var generateFilePath = dir + behaviourName + ".Designer.cs";

            if (mScriptKitInfo.IsNotNull())
            {
                if (mScriptKitInfo.Templates.IsNotNull() && mScriptKitInfo.Templates[1].IsNotNull())
                {
                    mScriptKitInfo.Templates[1].Generate(generateFilePath, behaviourName, UIKitSettingData.GetProjectNamespace(), panelCodeInfo);
                }
                mScriptKitInfo.HotScriptFilePath.CreateDirIfNotExists();
                mScriptKitInfo.HotScriptFilePath = mScriptKitInfo.HotScriptFilePath + "/" + behaviourName + mScriptKitInfo.HotScriptSuffix;
                if (File.Exists(mScriptKitInfo.HotScriptFilePath) == false && mScriptKitInfo.Templates.IsNotNull() && mScriptKitInfo.Templates[2].IsNotNull())
                {
                    mScriptKitInfo.Templates[2].Generate(mScriptKitInfo.HotScriptFilePath, behaviourName, UIKitSettingData.GetProjectNamespace(), panelCodeInfo);
                }
            }
            else
            {
                UIPanelDesignerTemplate.Write(behaviourName, dir, UIKitSettingData.GetProjectNamespace(), panelCodeInfo, UIKitSettingData.Load());
            }

            foreach (var elementCodeData in panelCodeInfo.ElementCodeDatas)
            {
                var elementDir = string.Empty;
                elementDir = elementCodeData.BindInfo.BindScript.GetBindType() == BindType.Element
                                        ? (dir + behaviourName + "/").CreateDirIfNotExists()
                                        : (Application.dataPath + "/" + UIKitSettingData.GetScriptsPath() + "/Components/").CreateDirIfNotExists();
                CreateUIElementCode(elementDir, elementCodeData);
            }
        }
        public static void Write(string name, string srcFilePath, string scriptNamespace,
                                 UIKitSettingData uiKitSettingData)
        {
            var scriptFile = srcFilePath;

            if (File.Exists(scriptFile))
            {
                return;
            }

            var writer = File.CreateText(scriptFile);

            var codeWriter = new FileCodeWriter(writer);


            var rootCode = new RootCode()
                           .Using("UnityEngine")
                           .Using("UnityEngine.UI")
                           .Using("QFramework")
                           .EmptyLine()
                           .Namespace(scriptNamespace, nsScope =>
            {
                nsScope.Class(name + "Data", "UIPanelData", false, false, classScope => { });

                nsScope.Class(name, "UIPanel", true, false, classScope =>
                {
                    classScope.CustomScope("protected override void ProcessMsg(int eventId, QMsg msg)", false,
                                           (function) => { function.Custom("throw new System.NotImplementedException();"); });

                    classScope.EmptyLine();
                    classScope.CustomScope("protected override void OnInit(IUIData uiData = null)", false,
                                           function =>
                    {
                        function.Custom("mData = uiData as {0} ?? new {0}();".FillFormat(name + "Data"));
                        function.Custom("// please add init code here");
                    });

                    classScope.EmptyLine();
                    classScope.CustomScope("protected override void OnOpen(IUIData uiData = null)", false,
                                           function => { });

                    classScope.EmptyLine();
                    classScope.CustomScope("protected override void OnShow()", false,
                                           function => { });
                    classScope.EmptyLine();
                    classScope.CustomScope("protected override void OnHide()", false,
                                           function => { });

                    classScope.EmptyLine();
                    classScope.CustomScope("protected override void OnClose()", false,
                                           function => { });
                });
            });

            rootCode.Gen(codeWriter);
            codeWriter.Dispose();
        }
        public static void DoCreateCodeFromScene(GameObject gameObject)
        {
            if (!gameObject)
            {
                Log.W("需要选择 GameObject");
                return;
            }

            if (gameObject.GetComponent <AbstractBind>() && !gameObject.GetComponent <ViewController>())
            {
                var parentController = gameObject.GetComponentInParent <ViewController>();

                if (parentController)
                {
                    gameObject = parentController.gameObject;
                }
            }

            Log.I("Create Code");

            var generateInfo = gameObject.GetComponent <ViewController>();

            var scriptsFolder = Application.dataPath + "/Scripts";

            if (generateInfo)
            {
                scriptsFolder = generateInfo.ScriptsFolder;
            }

            scriptsFolder.CreateDirIfNotExists();


            var panelCodeInfo = new PanelCodeInfo {
                GameObjectName = generateInfo.name
            };


            // 搜索所有绑定
            BindCollector.SearchBinds(gameObject.transform, "", panelCodeInfo);

            var uikitSettingData = UIKitSettingData.Load();

            ViewControllerTemplate.Write(generateInfo.ScriptName, scriptsFolder, generateInfo.Namespace,
                                         uikitSettingData);
            ViewControllerDesignerTemplate.Write(generateInfo.ScriptName, scriptsFolder, generateInfo.Namespace,
                                                 panelCodeInfo,
                                                 uikitSettingData);

            EditorPrefs.SetString("GENERATE_CLASS_NAME", generateInfo.ScriptName);
            EditorPrefs.SetString("GENERATE_NAMESPACE", generateInfo.Namespace.IsTrimNullOrEmpty() ? uikitSettingData.Namespace : generateInfo.Namespace);
            EditorPrefs.SetString("GAME_OBJECT_NAME", gameObject.name);
            AssetDatabase.Refresh();
        }
Example #10
0
        static void CreateCode()
        {
            var gameObject = Selection.objects.First() as GameObject;

            if (!gameObject)
            {
                Debug.LogWarning("需要选择 GameObject");
                return;
            }

            if (gameObject.GetComponent <Bind>() && !gameObject.GetComponent <ViewController>())
            {
                var parentController = gameObject.GetComponentInParent <ViewController>();

                if (parentController)
                {
                    gameObject = parentController.gameObject;
                }
            }

            Debug.Log("Create Code");

            var generateInfo = gameObject.GetComponent <ViewController>();

            var scriptsFolder = Application.dataPath + "/Scripts";

            if (generateInfo)
            {
                scriptsFolder = generateInfo.ScriptsFolder;
            }

            scriptsFolder.CreateDirIfNotExists();


            var panelCodeInfo = new PanelCodeInfo();

            panelCodeInfo.GameObjectName = generateInfo.name;

            // 搜索所有绑定
            BindCollector.SearchBinds(gameObject.transform, "", panelCodeInfo);

            var uikitSettingData = UIKitSettingData.Load();

            ViewControllerTemplate.Write(generateInfo.ScriptName, scriptsFolder, uikitSettingData);
            ViewControllerDesignerTemplate.Write(generateInfo.ScriptName, scriptsFolder, panelCodeInfo,
                                                 uikitSettingData);

            EditorPrefs.SetString("GENERATE_CLASS_NAME", generateInfo.ScriptName);
            EditorPrefs.SetString("GAME_OBJECT_NAME", gameObject.name);
            AssetDatabase.Refresh();
        }
        private void CreateUIPanelDesignerCode(string behaviourName, string uiUIPanelfilePath, PanelCodeInfo panelCodeInfo)
        {
            var dir = uiUIPanelfilePath.Replace(behaviourName + ".cs", "");
            var generateFilePath = dir + behaviourName + ".Designer.cs";

            if (mScriptKitInfo.IsNotNull())
            {
                if (mScriptKitInfo.Templates.IsNotNull() && mScriptKitInfo.Templates[1].IsNotNull())
                {
                    mScriptKitInfo.Templates[1].Generate(generateFilePath, behaviourName, UIKitSettingData.GetProjectNamespace(), panelCodeInfo);
                }
                mScriptKitInfo.HotScriptFilePath.CreateDirIfNotExists();
                mScriptKitInfo.HotScriptFilePath = mScriptKitInfo.HotScriptFilePath + "/" + behaviourName + mScriptKitInfo.HotScriptSuffix;
                if (File.Exists(mScriptKitInfo.HotScriptFilePath) == false && mScriptKitInfo.Templates.IsNotNull() && mScriptKitInfo.Templates[2].IsNotNull())
                {
                    mScriptKitInfo.Templates[2].Generate(mScriptKitInfo.HotScriptFilePath, behaviourName, UIKitSettingData.GetProjectNamespace(), panelCodeInfo);
                }
            }
            else
            {
                RegisteredTemplateGeneratorsFactory.RegisterTemplate <PanelCodeInfo, UIPanelDesignerTemplate>();

                var factory = new RegisteredTemplateGeneratorsFactory();

                var generators = factory.CreateGenerators(new UIGraph(), panelCodeInfo);

                CompilingSystem.GenerateFile(new FileInfo(generateFilePath), new CodeFileGenerator(UIKitSettingData.GetProjectNamespace())
                {
                    Generators = generators.ToArray()
                });

                RegisteredTemplateGeneratorsFactory.UnRegisterTemplate <PanelCodeInfo>();
            }

            foreach (var elementCodeData in panelCodeInfo.ElementCodeDatas)
            {
                var elementDir = string.Empty;
                elementDir = elementCodeData.BindInfo.BindScript.GetBindType() == BindType.Element
                                        ? (dir + behaviourName + "/").CreateDirIfNotExists()
                                        : (Application.dataPath + "/" + UIKitSettingData.GetScriptsPath() + "/Components/").CreateDirIfNotExists();
                CreateUIElementCode(elementDir, elementCodeData);
            }
        }
        private static void CreateUIElementCode(string generateDirPath, ElementCodeInfo elementCodeInfo)
        {
            var panelFilePathWhithoutExt = generateDirPath + elementCodeInfo.BehaviourName;

            if (File.Exists(panelFilePathWhithoutExt + ".cs") == false)
            {
                UIElementCodeTemplate.Generate(panelFilePathWhithoutExt + ".cs",
                                               elementCodeInfo.BehaviourName, UIKitSettingData.GetProjectNamespace(), elementCodeInfo);
            }

            UIElementCodeComponentTemplate.Generate(panelFilePathWhithoutExt + ".Designer.cs",
                                                    elementCodeInfo.BehaviourName, UIKitSettingData.GetProjectNamespace(), elementCodeInfo);

            foreach (var childElementCodeData in elementCodeInfo.ElementCodeDatas)
            {
                var elementDir = (panelFilePathWhithoutExt + "/").CreateDirIfNotExists();
                CreateUIElementCode(elementDir, childElementCodeData);
            }
        }
Example #13
0
        public static UIKitSettingData Load()
        {
            mConfigSavedDir.CreateDirIfNotExists();

            if (!File.Exists(mConfigSavedDir + mConfigSavedFileName))
            {
                using (var fileStream = File.Create(mConfigSavedDir + mConfigSavedFileName))
                {
                    fileStream.Close();
                }
            }

            var frameworkConfigData = SerializeHelper.LoadJson <UIKitSettingData>(mConfigSavedDir + mConfigSavedFileName);

            if (frameworkConfigData == null || string.IsNullOrEmpty(frameworkConfigData.Namespace))
            {
                frameworkConfigData = new UIKitSettingData {
                    Namespace = "QFramework.Example"
                };
            }

            return(frameworkConfigData);
        }
Example #14
0
        private void OnEnable()
        {
            mRootLayout = new VerticalLayout();

            EasyIMGUI.Button()
            .Text(LocaleText.Generate)
            .OnClick(() =>
            {
                CreateViewControllerCode.DoCreateCodeFromScene(((ViewController)target).gameObject);
                GUIUtility.ExitGUI();
            })
            .Height(30)
            .Parent(mRootLayout);

            if (mCodeGenerateInfo.ScriptsFolder.IsNullOrEmpty())
            {
                var setting = UIKitSettingData.Load();
                mCodeGenerateInfo.ScriptsFolder = "Assets" + setting.DefaultViewControllerScriptDir;
            }

            if (mCodeGenerateInfo.PrefabFolder.IsNullOrEmpty())
            {
                var setting = UIKitSettingData.Load();
                mCodeGenerateInfo.PrefabFolder = "Assets" + setting.DefaultViewControllerPrefabDir;
            }

            if (mCodeGenerateInfo.ScriptName.IsNullOrEmpty())
            {
                mCodeGenerateInfo.ScriptName = mCodeGenerateInfo.name;
            }

            if (mCodeGenerateInfo.Namespace.IsNullOrEmpty())
            {
                var setting = UIKitSettingData.Load();
                mCodeGenerateInfo.Namespace = setting.Namespace;
            }
        }
Example #15
0
        public static void SetObjectRef2Property(GameObject obj, string behaviourName, Assembly assembly,
                                                 List <IBind> processedMarks = null)
        {
            if (null == processedMarks)
            {
                processedMarks = new List <IBind>();
            }

            var iBind     = obj.GetComponent <IBind>();
            var className = string.Empty;

            if (iBind != null)
            {
                className = UIKitSettingData.GetProjectNamespace() + "." + iBind.ComponentName;

                // 这部分
                if (iBind.GetBindType() != BindType.DefaultUnityElement)
                {
                    var bind = obj.GetComponent <Bind>();
                    if (bind != null)
                    {
                        Object.DestroyImmediate(bind, true);
                    }
                }
            }
            else
            {
                className = UIKitSettingData.GetProjectNamespace() + "." + behaviourName;
            }

            var t = assembly.GetType(className);

            var com         = obj.GetComponent(t) ?? obj.AddComponent(t);
            var sObj        = new SerializedObject(com);
            var bindScripts = obj.GetComponentsInChildren <IBind>(true);

            foreach (var elementMark in bindScripts)
            {
                if (processedMarks.Contains(elementMark) || elementMark.GetBindType() == BindType.DefaultUnityElement)
                {
                    continue;
                }

                processedMarks.Add(elementMark);

                var uiType       = elementMark.ComponentName;
                var propertyName = string.Format("{0}", elementMark.Transform.gameObject.name);

                if (sObj.FindProperty(propertyName) == null)
                {
                    Log.I("sObj is Null:{0} {1} {2}", propertyName, uiType, sObj);
                    continue;
                }

                sObj.FindProperty(propertyName).objectReferenceValue = elementMark.Transform.gameObject;
                SetObjectRef2Property(elementMark.Transform.gameObject, elementMark.ComponentName, assembly, processedMarks);
            }

            var marks = obj.GetComponentsInChildren <IBind>(true);

            foreach (var elementMark in marks)
            {
                if (processedMarks.Contains(elementMark))
                {
                    continue;
                }

                processedMarks.Add(elementMark);

                var propertyName = elementMark.Transform.name;
                sObj.FindProperty(propertyName).objectReferenceValue = elementMark.Transform.gameObject;
            }

            sObj.ApplyModifiedPropertiesWithoutUndo();
        }
 public UIKitSettingView()
 {
     mUiKitSettingData = UIKitSettingData.Load();
 }
        private void CreateUIPanelCode(GameObject uiPrefab, string uiPrefabPath, PanelCodeInfo panelCodeInfo)
        {
            if (null == uiPrefab)
            {
                return;
            }

            var behaviourName = uiPrefab.name;

            var strFilePath = CodeGenUtil.GenSourceFilePathFromPrefabPath(uiPrefabPath, behaviourName);

            if (mScriptKitInfo.IsNotNull())
            {
                if (File.Exists(strFilePath) == false)
                {
                    if (mScriptKitInfo.Templates.IsNotNull() && mScriptKitInfo.Templates[0].IsNotNull())
                    {
                        mScriptKitInfo.Templates[0].Generate(strFilePath, behaviourName, UIKitSettingData.GetProjectNamespace(), null);
                    }
                }
            }
            else
            {
                if (File.Exists(strFilePath) == false)
                {
                    RegisteredTemplateGeneratorsFactory.RegisterTemplate <PanelCodeInfo, UIPanelDataTemplate>();
                    RegisteredTemplateGeneratorsFactory.RegisterTemplate <PanelCodeInfo, UIPanelTemplate>();

                    var factory = new RegisteredTemplateGeneratorsFactory();

                    var generators = factory.CreateGenerators(new UIGraph(), panelCodeInfo);

                    CompilingSystem.GenerateFile(new FileInfo(strFilePath), new CodeFileGenerator(UIKitSettingData.GetProjectNamespace())
                    {
                        Generators = generators.ToArray()
                    });

                    RegisteredTemplateGeneratorsFactory.UnRegisterTemplate <PanelCodeInfo>();
                }
            }

            CreateUIPanelDesignerCode(behaviourName, strFilePath, panelCodeInfo);
            Debug.Log(">>>>>>>Success Create UIPrefab Code: " + behaviourName);
        }
        private void OnEnable()
        {
            if (mSerializedObject.IsNull())
            {
                mSerializedObject = new SerializedObject(target);
            }

            mRootLayout = new VerticalLayout();

            if (mCodeGenerateInfo.Namespace.IsNullOrEmpty())
            {
                mCodeGenerateInfo.Namespace = UIKitSettingData.GetProjectNamespace();
            }

            if (mCodeGenerateInfo.ScriptsFolder.IsNullOrEmpty())
            {
                mCodeGenerateInfo.ScriptsFolder = "Assets" + UIKitSettingData.GetScriptsPath();
            }

            if (mCodeGenerateInfo.ScriptName.IsNullOrEmpty())
            {
                mCodeGenerateInfo.ScriptName = mCodeGenerateInfo.gameObject.name;
            }

            new HorizontalLayout()
            .AddChild(EasyIMGUI.Label().Text(LocaleText.Namespace).Width(150))
            .AddChild(EasyIMGUI.TextField().Text(mCodeGenerateInfo.Namespace).Do(v =>
            {
                v.Content.Bind((newValue) =>
                {
                    mCodeGenerateInfo.Namespace = newValue;
                    EditorUtility.SetDirty(mCodeGenerateInfo);
                });
            }))
            .AddTo(mRootLayout);

            new HorizontalLayout()
            .AddChild(EasyIMGUI.Label().Text(LocaleText.ScriptName)).Width(150)
            .AddChild(EasyIMGUI.TextField().Text(mCodeGenerateInfo.ScriptName).Do(v =>
            {
                v.Content.Bind((newValue) =>
                {
                    mCodeGenerateInfo.ScriptName = newValue;
                    EditorUtility.SetDirty(mCodeGenerateInfo);
                });
            }))
            .AddTo(mRootLayout);


            new HorizontalLayout()
            .AddChild(EasyIMGUI.Label().Text(LocaleText.ScriptsFolder).Width(150))
            .AddChild(EasyIMGUI.TextField().Text(mCodeGenerateInfo.ScriptsFolder).Do(v =>
            {
                v.Content.Bind((newValue) =>
                {
                    mCodeGenerateInfo.ScriptsFolder = newValue;
                    EditorUtility.SetDirty(mCodeGenerateInfo);
                });

                mScriptFolderView = v;
            }))
            .AddTo(mRootLayout);

            EasyIMGUI.Custom().OnGUI(() =>
            {
                EditorGUILayout.Space();
                EditorGUILayout.LabelField("请将要生成脚本的文件夹拖到下边区域 或 自行填写目录到上一栏中");
                var sfxPathRect    = EditorGUILayout.GetControlRect();
                sfxPathRect.height = 200;
                GUI.Box(sfxPathRect, string.Empty);
                EditorGUILayout.LabelField(string.Empty, GUILayout.Height(185));
                if (
                    Event.current.type == EventType.DragUpdated &&
                    sfxPathRect.Contains(Event.current.mousePosition)
                    )
                {
                    //改变鼠标的外表
                    DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
                    if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0)
                    {
                        if (DragAndDrop.paths[0] != "")
                        {
                            var newPath = DragAndDrop.paths[0];
                            mScriptFolderView.Content.Value = newPath;
                            AssetDatabase.SaveAssets();
                            AssetDatabase.Refresh();
                            EditorSceneManager.MarkSceneDirty(EditorSceneManager.GetActiveScene());
                        }
                    }
                }

                var fileFullPath = mCodeGenerateInfo.ScriptsFolder + "/" + mCodeGenerateInfo.ScriptName + ".cs";
                if (File.Exists(mCodeGenerateInfo.ScriptsFolder + "/" + mCodeGenerateInfo.ScriptName + ".cs"))
                {
                    var scriptObject = AssetDatabase.LoadAssetAtPath <MonoScript>(fileFullPath);
                    if (GUILayout.Button("打开脚本", GUILayout.Height(30)))
                    {
                        AssetDatabase.OpenAsset(scriptObject);
                    }

                    if (GUILayout.Button("选择脚本", GUILayout.Height(30)))
                    {
                        Selection.objects = new Object[] { scriptObject };
                    }
                }
            }).AddTo(mRootLayout);

            EasyIMGUI.Button()
            .Text(LocaleText.Generate)
            .OnClick(() =>
            {
                if (mCodeGenerateInfo.GetComponent <UIDefaultPanel>())
                {
                    CreateILBehaviourCode.DoCreateCodeFromScene(mCodeGenerateInfo.gameObject, true);
                }
                else
                {
                    CreateILBehaviourCode.DoCreateCodeFromScene(mCodeGenerateInfo.gameObject);
                }
            })
            .Height(30)
            .AddTo(mRootLayout);
        }
        public static void Write(string name, string scriptsFolder, string scriptNamespace, PanelCodeInfo panelCodeInfo,
                                 UIKitSettingData uiKitSettingData)
        {
            var scriptFile = scriptsFolder + "/{0}.Designer.cs".FillFormat(name);

            var writer = File.CreateText(scriptFile);

            var root = new RootCode()
                       .Using("System")
                       .Using("UnityEngine")
                       .Using("UnityEngine.UI")
                       .Using("QFramework")
                       .EmptyLine()
                       .Namespace(scriptNamespace.IsTrimNullOrEmpty()
                    ? uiKitSettingData.Namespace
                    : scriptNamespace, ns =>
            {
                ns.Custom("// Generate Id:{0}".FillFormat(Guid.NewGuid().ToString()));
                ns.Class(name, null, true, false, (classScope) =>
                {
                    classScope.Custom("public const string Name = \"" + name + "\";");
                    classScope.EmptyLine();

                    foreach (var bindInfo in panelCodeInfo.BindInfos)
                    {
                        if (bindInfo.BindScript.Comment.IsNotNullAndEmpty())
                        {
                            classScope.Custom("/// <summary>");
                            classScope.Custom("/// " + bindInfo.BindScript.Comment);
                            classScope.Custom("/// </summary>");
                        }

                        classScope.Custom("[SerializeField]");
                        classScope.Custom("public " + bindInfo.BindScript.ComponentName + " " + bindInfo.Name +
                                          ";");
                    }

                    classScope.EmptyLine();
                    classScope.Custom("private " + name + "Data mPrivateData = null;");

                    classScope.EmptyLine();

                    classScope.CustomScope("protected override void ClearUIComponents()", false, (function) =>
                    {
                        foreach (var bindInfo in panelCodeInfo.BindInfos)
                        {
                            function.Custom(bindInfo.Name + " = null;");
                        }

                        function.EmptyLine();
                        function.Custom("mData = null;");
                    });

                    classScope.EmptyLine();

                    classScope.CustomScope("public " + name + "Data Data", false,
                                           (property) =>
                    {
                        property.CustomScope("get", false, (getter) => { getter.Custom("return mData;"); });
                    });

                    classScope.EmptyLine();


                    classScope.CustomScope(name + "Data mData", false, (property) =>
                    {
                        property.CustomScope("get", false,
                                             (getter) =>
                        {
                            getter.Custom("return mPrivateData ?? (mPrivateData = new " + name + "Data());");
                        });

                        property.CustomScope("set", false, (setter) =>
                        {
                            setter.Custom("mUIData = value;");
                            setter.Custom("mPrivateData = value;");
                        });
                    });
                });
            });

            var codeWriter = new FileCodeWriter(writer);

            root.Gen(codeWriter);
            codeWriter.Dispose();
        }
Example #20
0
        static void AddComponent2GameObject()
        {
//            Debug.Log("DidReloadScripts");
            var generateClassName = EditorPrefs.GetString("GENERATE_CLASS_NAME");
            var gameObjectName    = EditorPrefs.GetString("GAME_OBJECT_NAME");

//            Debug.Log(generateClassName);

            if (string.IsNullOrEmpty(generateClassName))
            {
//                Debug.Log("不继续操作");
                EditorPrefs.DeleteKey("GENERATE_CLASS_NAME");
                EditorPrefs.DeleteKey("GAME_OBJECT_NAME");
            }
            else
            {
//                Debug.Log("继续操作");

                var assemblies = AppDomain.CurrentDomain.GetAssemblies();

                var defaultAssembly = assemblies.First(assembly => assembly.GetName().Name == "Assembly-CSharp");

                var typeName = UIKitSettingData.Load().Namespace + "." + generateClassName;

                var type = defaultAssembly.GetType(typeName);

                if (type == null)
                {
                    Debug.Log("编译失败");
                    return;
                }

                Debug.Log(type);

                var gameObject = GameObject.Find(gameObjectName);

                var scriptComponent = gameObject.GetComponent(type);

                if (!scriptComponent)
                {
                    scriptComponent = gameObject.AddComponent(type);
                }

                var serialiedScript = new SerializedObject(scriptComponent);

                var panelCodeInfo = new PanelCodeInfo();

                panelCodeInfo.GameObjectName = gameObjectName;

                // 搜索所有绑定
                BindCollector.SearchBinds(gameObject.transform, "", panelCodeInfo);

                foreach (var bindInfo in panelCodeInfo.BindInfos)
                {
                    var name = bindInfo.Name;

                    var componentName = bindInfo.BindScript.ComponentName.Split('.').Last();

                    serialiedScript.FindProperty(name).objectReferenceValue =
                        gameObject.transform.Find(bindInfo.PathToElement)
                        .GetComponent(componentName);
                }


                var codeGenerateInfo = gameObject.GetComponent <ViewController>();

                if (codeGenerateInfo)
                {
                    serialiedScript.FindProperty("ScriptsFolder").stringValue = codeGenerateInfo.ScriptsFolder;
                    serialiedScript.FindProperty("PrefabFolder").stringValue  = codeGenerateInfo.PrefabFolder;
                    serialiedScript.FindProperty("GeneratePrefab").boolValue  = codeGenerateInfo.GeneratePrefab;
                    serialiedScript.FindProperty("ScriptName").stringValue    = codeGenerateInfo.ScriptName;

                    var generatePrefab = codeGenerateInfo.GeneratePrefab;
                    var prefabFolder   = codeGenerateInfo.PrefabFolder;

                    var fullPrefabFolder = prefabFolder.Replace("Assets", Application.dataPath);

                    if (codeGenerateInfo.GetType() != type)
                    {
                        DestroyImmediate(codeGenerateInfo, false);
                    }

                    serialiedScript.ApplyModifiedPropertiesWithoutUndo();

                    if (generatePrefab)
                    {
                        fullPrefabFolder.CreateDirIfNotExists();

                        var genereateFolder = fullPrefabFolder + "/" + gameObject.name + ".prefab";
#if UNITY_2018_3_OR_NEWER
                        PrefabUtility.SaveAsPrefabAssetAndConnect(gameObject,
                                                                  fullPrefabFolder + "/" + gameObject.name + ".prefab",
                                                                  InteractionMode.AutomatedAction);
#else
                        genereateFolder = prefabFolder + "/" + gameObject.name + ".prefab";
                        PrefabUtility.CreatePrefab(genereateFolder, gameObject, ReplacePrefabOptions.ConnectToPrefab);
#endif
                    }
                }
                else
                {
                    serialiedScript.FindProperty("ScriptsFolder").stringValue = "Assets/Scripts";
                    serialiedScript.ApplyModifiedPropertiesWithoutUndo();
                }

                EditorPrefs.DeleteKey("GENERATE_CLASS_NAME");
                EditorPrefs.DeleteKey("GAME_OBJECT_NAME");

                EditorUtils.MarkCurrentSceneDirty();
            }
        }