Ejemplo n.º 1
0
        private static void AddScriptToView(string viewType)
        {
            var prefab    = Selection.gameObjects[0];
            var directory = AssetDatabase.GetAssetPath(prefab);

            // ReSharper disable once PossibleNullReferenceException
            var assemblyName = "Assembly-My-MVP";

            var types = Assembly.Load(assemblyName).GetTypes();

            foreach (var type in types)
            {
                if (type.Name != Selection.gameObjects[0].name + viewType)
                {
                    continue;
                }

                var component = prefab.GetComponent(type);
                if (component == null)
                {
                    component = prefab.AddComponent(type);
                }
                var fieldInfos = component.GetType().GetFields(BindingFlags.NonPublic |
                                                               BindingFlags.Instance | BindingFlags.Public);
                foreach (var field in fieldInfos)
                {
                    if (field.Name == "Presenter")
                    {
                        continue;
                    }
                    var gameObjectName = NameConverter.ToPascalFromPrivate(field.Name);

                    if (field.Name.Contains("ToggleGroup"))
                    {
                        var toggleGroup = prefab.transform.Find(gameObjectName);

                        var value    = (IList)field.GetValue(component);
                        var newArray = Array.CreateInstance(field.FieldType.GetElementType(), toggleGroup.childCount);

                        for (int i = 0; i < toggleGroup.childCount; i++)
                        {
                            var componentReference = toggleGroup.GetChild(i).GetComponent(field.FieldType.GetElementType());
                            if (componentReference != null)
                            {
                                newArray.SetValue(componentReference, i);
                            }
                        }
                        field.SetValue(component, newArray);
                    }
                    else if (field.Name.Contains("Text") || field.Name.Contains("Image") || field.Name.Contains("Button"))
                    {
                        var componentReference = FindFromAllChild(prefab.transform, gameObjectName).GetComponent(field.FieldType);
                        field.SetValue(component, componentReference);
                    }

                    AssetDatabase.Refresh();
                }
            }

            AssetDatabase.Refresh();
        }