Exemplo n.º 1
0
        public void OnDrop(Inventory inv, bool tss, int slot, int amount, bool dbui, Vector3?pos)
        {
            if ((inv.interactiable & InventoryController.DropInvFlags) != InventoryController.DropInvFlags)
            {
                return;
            }

            if (optionalOnDropBehaviour == null)
            {
                InventoryHandler.DropItemEventArgs dea = new InventoryHandler.DropItemEventArgs(inv, tss, slot, this, amount, dbui, pos.GetValueOrDefault(), true);

                InventoryHandler.current.Broadcast(BroadcastEventType.DropItem, dea: dea);
            }
            else
            {
                InventoryHandler.DropItemEventArgs dea = new InventoryHandler.DropItemEventArgs(inv, tss, slot, this, amount, dbui, pos.GetValueOrDefault(), false);
                object[] tmp = new object[2] {
                    this, dea
                };

                BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;

                MethodInfo monoMethod = optionalOnDropBehaviour.GetClass().GetMethod("OnDropItem", flags);

                if (monoMethod == null)
                {
                    Debug.LogError($"The script provided ({optionalOnDropBehaviour.name}) on item {itemName} does not contain, or its not accesible, the expected function OnDropItem.\n Check if this function exists and if the provided script derives from DropBehaviour");
                }
                else
                {
                    monoMethod.Invoke(Activator.CreateInstance(optionalOnDropBehaviour.GetClass()), tmp);
                }
            }
        }
    private void Start()
    {
        if (platformTopCollider != null && topCustomAction != null && topCustomAction.GetClass().IsSubclassOf(typeof(OnCollisionCustomAction)))
        {
            OnCollisionCustomAction customAction = platformTopCollider.AddComponent(topCustomAction.GetClass()) as OnCollisionCustomAction;
            customAction.InitializeData();
        }

        if (platformBottomCollider != null && bottomCustomAction != null && bottomCustomAction.GetClass().IsSubclassOf(typeof(OnCollisionCustomAction)))
        {
            OnCollisionCustomAction customAction = platformBottomCollider.AddComponent(bottomCustomAction.GetClass()) as OnCollisionCustomAction;
            customAction.InitializeData();
        }

        if (platformRightCollider != null && rightCustomAction != null && rightCustomAction.GetClass().IsSubclassOf(typeof(OnCollisionCustomAction)))
        {
            OnCollisionCustomAction customAction = platformRightCollider.AddComponent(rightCustomAction.GetClass()) as OnCollisionCustomAction;
            customAction.InitializeData();
        }

        if (platformLeftCollider != null && leftCustomAction != null && leftCustomAction.GetClass().IsSubclassOf(typeof(OnCollisionCustomAction)))
        {
            OnCollisionCustomAction customAction = platformLeftCollider.AddComponent(leftCustomAction.GetClass()) as OnCollisionCustomAction;
            customAction.InitializeData();
        }
    }
Exemplo n.º 3
0
        /// <summary>
        /// Returns a collection of MonoScripts whose class inherits from T.
        /// <returns>A collection of MonoScript whose class inherits from T.</returns>
        /// </summary>
        public static MonoScript[] GetScripts <T>()
        {
            // Try get loaded MonoScripts
            MonoScript[] loadedScripts = null;
            if (s_LoadedScripts.TryGetValue(typeof(T), out loadedScripts))
            {
                return(loadedScripts);
            }

            // Load all MonoScripts
            Resources.LoadAll(string.Empty, typeof(MonoScript));

            var scripts = new List <MonoScript>();

            // Get all MonoScripts
            foreach (UnityEngine.Object obj in Resources.FindObjectsOfTypeAll(typeof(MonoScript)))
            {
                MonoScript mono = obj as MonoScript;
                if (mono != null && mono.GetClass() != null && mono.GetClass().IsSubclassOf(typeof(T)) && !mono.GetClass().IsAbstract)
                {
                    scripts.Add(mono);
                }
            }

            // Sort scripts by name
            scripts.Sort((MonoScript s1, MonoScript s2) => s1.GetClass().ToString().CompareTo(s2.GetClass().ToString()));

            // Add scripts to dictionary
            loadedScripts = scripts.ToArray();
            s_LoadedScripts.Add(typeof(T), loadedScripts);

            return(loadedScripts);
        }
Exemplo n.º 4
0
        static public void CustomizeInterface()
        {
            string     path           = "";
            string     name           = "";
            MonoScript renderedScript = null;

            if (Selection.activeObject is MonoScript)
            {
                renderedScript = (MonoScript)Selection.activeObject;
                name           = renderedScript.GetClass().ToString();
                path           = AssetDatabase.GetAssetPath(renderedScript);

                if (File.Exists(path))
                {
                    path = Path.GetDirectoryName(path);
                }

                path  = path + "/Editor/";
                name += "Interface";
            }

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            Utils.CreateEditorScript(renderedScript.GetClass(), path);
        }
        private void OnGUI()
        {
            EditorGUILayout.BeginVertical();

            EditorGUILayout.LabelField("Drag a ScriptableObject to create an instance of it");

            EditorGUILayout.Space();

            _scriptable = EditorGUILayout.ObjectField(_scriptable, typeof(MonoScript), true) as MonoScript;

            EditorGUILayout.Space();

            if (_scriptable == null || _scriptable.GetClass() == null || !_scriptable.GetClass().BaseType.Equals(typeof(ScriptableObject)))
            {
                _scriptable = null;
                EditorGUILayout.LabelField("You need a subclass of a ScriptableObject");
            }
            else if (GUILayout.Button("Create Instance") && _scriptable != null)
            {
                ScriptableObjectUtility.CreateAsset(_scriptable.GetClass());
            }

            EditorGUILayout.Space();

            EditorGUILayout.EndVertical();
        }
Exemplo n.º 6
0
        /// <summary>
        /// 建立 Scriptable Asset
        /// </summary>
        /// <returns>是否成功建立</returns>
        public bool CreateScriptableAssets(string scriptableScriptName, string scriptableAssetName)
        {
            _config = ClientDataBaseManager.Instance.m_config;
            MonoScript script = AssetDatabase.LoadAssetAtPath <MonoScript>(_config.GetScriptableScriptsPath() + scriptableScriptName);

            if (script == null || script.GetClass() == null)
            {
                Debug.LogError(string.Format("Scriptable Script is Null. [Path:{0}]", _config.GetScriptableScriptsPath() + scriptableScriptName));
                return(false);
            }

            string path = _config.GetScriptableAssetPath() + scriptableAssetName;

            UtilityEditor.CreateFolder(_config.GetScriptableAssetPath());

            Object _Object = ScriptableObject.CreateInstance(script.GetClass());

            AssetDatabase.CreateAsset(_Object, path);

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

            Debug.Log(string.Format("[Scriptable Asset] is Create.\nFile:[{0}] Path:[{1}]", scriptableAssetName, _config.GetScriptableAssetPath()));

            //資料讀取
            ScriptableObjectBase scriptableObjectBase = AssetDatabase.LoadAssetAtPath <ScriptableObjectBase>(path);

            return(scriptableObjectBase.LoadGameTable(true));
        }
Exemplo n.º 7
0
    private void MoveFiles()
    {
        if (scriptFolder == null || editorFolder == null)
        {
            ShowNotification(new GUIContent("Folders not specified. Please assing a valid folder"), 3);
            return;
        }

        string appPath = Application.dataPath.Replace("Assets", "") + AssetDatabase.GetAssetPath(scriptFolder);

        string[] assetPaths  = Directory.GetFiles(appPath, "*.cs", SearchOption.AllDirectories);
        int      assetsMoved = 0;

        try
        {
            for (int i = 0; i < assetPaths.Length; i++)
            {
                if (EditorUtility.DisplayCancelableProgressBar("Moving editor scripts", "Moving folders... (" + i + "/" + assetPaths.Length + ")", (float)i / (float)assetPaths.Length))
                {
                    break;
                }

                string path       = AssetDatabase.GetAssetPath(scriptFolder) + assetPaths[i].Replace(appPath, "").Replace('\\', '/');
                string targetPath = AssetDatabase.GetAssetPath(editorFolder) + assetPaths[i].Replace(appPath, "").Replace('\\', '/');
                Object asset      = AssetDatabase.LoadAssetAtPath(path, typeof(Object));

                if (asset is MonoScript)
                {
                    MonoScript script = asset as MonoScript;
                    if (script != null && script.GetClass() != null &&
                        (script.GetClass().IsSubclassOf(typeof(UnityEditor.Editor)) ||
                         script.GetClass().IsSubclassOf(typeof(EditorWindow)) ||
                         script.GetClass().IsSubclassOf(typeof(PropertyDrawer)) ||
                         IsParentClassEditor(script)))
                    {
                        CreatePath(targetPath);
                        string error = AssetDatabase.ValidateMoveAsset(path, targetPath);
                        if (string.IsNullOrEmpty(error))
                        {
                            Undo.RegisterCompleteObjectUndo(script, "Move " + script.name + " to editor folder");
                            AssetDatabase.MoveAsset(path, targetPath);
                            assetsMoved++;
                        }
                        else
                        {
                            Debug.LogError(error);
                        }
                    }
                }
            }
        }
        catch (System.Exception e) { Debug.LogException(e); }

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

        ShowNotification(new GUIContent("Moved " + assetsMoved + " files to editor folder"), 3);

        EditorUtility.ClearProgressBar();
    }
Exemplo n.º 8
0
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            if (property.propertyType == SerializedPropertyType.String)
            {
                Rect r         = EditorGUI.PrefixLabel(position, label);
                Rect labelRect = position;
                labelRect.xMax = r.xMin;
                position       = r;
                m_ViewString   = GUI.Toggle(labelRect, m_ViewString, "", "label");
                if (m_ViewString)
                {
                    property.stringValue = EditorGUI.TextField(position, property.stringValue);
                    return;
                }
                MonoScript script = null;

                if (!string.IsNullOrEmpty(property.stringValue))
                {
                    string typeName = Type.GetType(property.stringValue).FullName;
                    if (!string.IsNullOrEmpty(typeName))
                    {
                        m_ScriptCache.TryGetValue(typeName, out script);
                        if (script == null)
                        {
                            GUI.color = Color.red;
                        }
                    }
                }
                script = (MonoScript)EditorGUI.ObjectField(position, script, typeof(MonoScript), false);
                if (GUI.changed)
                {
                    if (script != null)
                    {
                        var type = script.GetClass();
                        MonoScriptAttribute attr = (MonoScriptAttribute)attribute;
                        if (attr.type != null && !attr.type.IsAssignableFrom(type))
                        {
                            type = null;
                        }
                        if (type != null)
                        {
                            var targetClass = script.GetClass();
                            property.stringValue = targetClass.AssemblyQualifiedName;
                        }
                        else
                        {
                            Debug.LogWarning("The script file " + script.name + " doesn't contain an assignable class");
                        }
                    }
                    else
                    {
                        property.stringValue = "";
                    }
                }
            }
            else
            {
                GUI.Label(position, "The MonoScript attribute can only be used on string variables");
            }
        }
Exemplo n.º 9
0
        public virtual void OnUse(Inventory inv, int slot)
        {
            InventoryHandler.UseItemEventArgs uea = new InventoryHandler.UseItemEventArgs(inv, this, slot);
            if (onUseFunc == null)
            {
                InventoryHandler.current.Broadcast(BroadcastEventType.UseItem, uea: uea);
                return;
            }

            object[] tmp = new object[2] {
                this, uea
            };

            BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;

            MethodInfo monoMethod = onUseFunc.GetClass().GetMethod("OnUse", flags);

            if (monoMethod == null)
            {
                Debug.LogError($"The script provided ({onUseFunc.name}) on item {itemName} does not contain, or its not accesible, the expected function OnUse.\n Check if this function exists and if the provided script derives from IUsable");
            }
            else
            {
                monoMethod.Invoke(Activator.CreateInstance(onUseFunc.GetClass()), tmp);
            }

            InventoryHandler.current.Broadcast(BroadcastEventType.UseItem, uea: uea);
        }
Exemplo n.º 10
0
    void DoJob()
    {
        GUI.color = Color.white;
        msg       = "Search for : <color=#00ffffff>" + searchType.GetClass().ToString() + "</color>" + "\n";

        //Get all the scenes in project
        var scenesGUIDs = AssetDatabase.FindAssets("t:Scene", new[] { "Assets/" });

        msg += "Search in : " + scenesGUIDs.Length + " scenes" + "\n";

        if (result == null)
        {
            result = new Dictionary <string, int>();
        }
        result.Clear();
        for (int i = 0; i < scenesGUIDs.Length; i++)
        {
            //Open the scene
            string scenePath = AssetDatabase.GUIDToAssetPath(scenesGUIDs[i]);
            OpenScene(scenePath);
            Scene currentScene = EditorSceneManager.GetSceneAt(0);
            EditorSceneManager.SetActiveScene(currentScene);

            //See if the scene contains the component we search for
            Object[] subsceneObjs = UnityEngine.GameObject.FindObjectsOfType(searchType.GetClass(), true);
            if (subsceneObjs.Length > 0)
            {
                result.Add(scenePath, subsceneObjs.Length);
            }
        }

        msg += "Result : " + result.Count + " scenes" + "\n";
        msg += "\n";
    }
Exemplo n.º 11
0
    // Use this for initialization
    void Start()
    {
        /*RuntimeScript = ScriptObject.GetComponent(CompileTimeScript.GetClass()); //The non-generic form of GetComponent, mothafuckaz!
         * if (RuntimeScript == null)
         * {
         *  //Good to put in a hard assert here
         *  Debug.LogError(name + ": Scriptobject " + ScriptObject.name + " doesn't contain script type " + CompileTimeScript.name + "!");
         * }*/

        //Cache MethodInfos for the register methods, so we can make them generic later without repeating these particular reflection calls.
        _displayRegisterMethod   = typeof(OldConsole).GetMethod("RegisterDisplayHelper", BindingFlags.Instance | BindingFlags.NonPublic);
        _controlRegisterMethod   = typeof(OldConsole).GetMethod("RegisterControlHelper", BindingFlags.Instance | BindingFlags.NonPublic);
        _displayDeregisterMethod = typeof(OldConsole).GetMethod("DeregisterDisplayHelper", BindingFlags.Instance | BindingFlags.NonPublic);
        _controlDeregisterMethod = typeof(OldConsole).GetMethod("DeregisterControlHelper", BindingFlags.Instance | BindingFlags.NonPublic);

        #region Hard-Coded Test
        if (false) //Change to turn this test on/off.
        {
            //Hard-code adding a float function to make sure this works conceptually.
            MethodInfo[] methods = CompileTimeScript.GetClass().GetMethods(BindingFlags.Instance | BindingFlags.Public); //Should be the last time we call CompileTimeScript at runtime.

            //TEST: Find the base type of TestDisplay, cached for faster iteration when we loop through methods.
            Type disptype = (Type)TestDisplay.GetType().GetMethod("get_DisplayType").Invoke(TestDisplay, null);
            Type conttype = (Type)TestControl.GetType().GetMethod("get_ControlType").Invoke(TestControl, null);



            //Skip any that aren't from the user-created component
            int validmethods = 0;
            for (int i = 0; i < methods.Length; i++)
            {
                if (methods[i].DeclaringType == typeof(MonoBehaviour) || methods[i].DeclaringType.IsAssignableFrom(typeof(MonoBehaviour)))
                {
                    continue;
                }
                validmethods++;

                //Now for the actual hard-coded testing.
                //Display:
                if (methods[i].ReturnType == disptype)
                {
                    RegisterIntoDisplay(methods[i], TestDisplay, disptype);
                }
                //Control:
                ParameterInfo[] paramarray = methods[i].GetParameters();
                if (paramarray.Length == 1 && paramarray[0].ParameterType == conttype)
                {
                    print("Found control match: " + conttype + " in " + methods[i].Name);
                    RegisterIntoControl(methods[i], TestControl, conttype);
                }
            }
        }
        #endregion

        //Actually set up the bindings
        SetUpBindings();
    }
Exemplo n.º 12
0
    public List <MonoScript> Importable(string folderName)
    {
        string[]          filePaths         = Directory.GetFiles(Application.dataPath + "/" + folderName, "*.cs", SearchOption.AllDirectories);
        List <MonoScript> ret               = new List <MonoScript>();
        List <string>     existingInspector = new List <string>();

        foreach (string f in filePaths)
        {
            string file = f.Replace(Application.dataPath, "");
            file = "Assets" + file.Replace("\\", "/");
            Object obj = AssetDatabase.LoadAssetAtPath(file, typeof(MonoScript));

            if (obj == null)
            {
                continue;
            }

            MonoScript m  = (MonoScript)obj;
            Type       cl = m.GetClass();

            if (cl != null && cl.IsSubclassOf(typeof(Editor)))
            {
                object[] attributes = m.GetClass().GetCustomAttributes(typeof(CustomEditor), false);
                foreach (CustomEditor ce in attributes)
                {
                    FieldInfo p    = ce.GetType().GetField("m_InspectedType");
                    Type      type = p.GetValue(ce) as Type;
                    existingInspector.Add(type.Name);
                }
            }
        }

        foreach (string f in filePaths)
        {
            string file = f.Replace(Application.dataPath, "");
            file = "Assets" + file.Replace("\\", "/");

            Object obj = AssetDatabase.LoadAssetAtPath(file, typeof(MonoScript));

            if (obj == null)
            {
                continue;
            }

            MonoScript m  = (MonoScript)obj;
            Type       cl = m.GetClass();

            if (cl != null && CanHaveEditor(cl) && !existingInspector.Contains(m.name))
            {
                ret.Add(m);
            }
        }

        return(ret);
    }
Exemplo n.º 13
0
 /// <summary>
 /// 批量添加组件
 /// </summary>
 public void AddThisTagComponents()
 {
     GameObject[] a = GameObject.FindGameObjectsWithTag(tag);
     foreach (var item in a)
     {
         if (item.GetComponent(_scriptObj.GetClass()) == null)
         {
             item.AddComponent(_scriptObj.GetClass());
         }
     }
 }
Exemplo n.º 14
0
 static bool ValidateInit()
 {
     if (Selection.activeObject.GetType() == typeof(MonoScript))
     {
         MonoScript script = (MonoScript)Selection.activeObject;
         if (script.GetClass().BaseType == typeof(Node))
         {
             previewNodeType = script.GetClass();
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 15
0
    string[] FindSceneObjectsWith(MonoScript component)
    {
        string[] allAssets = AssetDatabase.GetAllAssetPaths();

        System.Type componentType = component.GetClass();

        List <string> searchResult = new List <string>();

        objRefs = new List <Object>();

        for (int i = 0; i < allAssets.Length; i++)
        {
            string currentPath = allAssets[i];
            if (currentPath.StartsWith("Assets")) //Remove annoying warning in editor for incorrect paths
            {
                System.Type assetType = AssetDatabase.GetMainAssetTypeAtPath(currentPath);

                // In open Scenes
                if (assetType == typeof(SceneAsset))
                {
                    SceneAsset scene = AssetDatabase.LoadAssetAtPath <SceneAsset>(currentPath);
                    Scene      s     = SceneManager.GetSceneByName(scene.name);
                    if (s.IsValid())
                    {
                        GameObject[] rootObjects = s.GetRootGameObjects();

                        for (int j = 0; j < rootObjects.Length; j++)
                        {
                            GameObject currentObject = rootObjects[j];

                            var scripts = currentObject.GetComponentsInChildren(componentType, true);
                            if (scripts.Length > 0)
                            {
                                for (int k = 0; k < scripts.Length; k++)
                                {
                                    GameObject currentSubObject = scripts[k].gameObject;
                                    string     r = string.Format("'{0}' {1} has '{2}' attached, in '{3}'",
                                                                 currentSubObject.name,
                                                                 (currentSubObject.GetInstanceID() == currentObject.GetInstanceID() ? "" : " (parent: " + currentObject.name + ")"),
                                                                 component.GetClass().ToString(),
                                                                 s.name);
                                    searchResult.Add(r);
                                }
                            }
                        }
                    }
                }
            }
        }
        return(searchResult.ToArray());
    }
Exemplo n.º 16
0
        void DrawRule <T>(string caption, ref bool ruleEnabled, ref string ruleClassName) where T : ScriptableObject
        {
            GUI.enabled = true;
            EditorGUILayout.BeginHorizontal();
            GUILayout.Space(CATEGORY_SPACING);
            ruleEnabled = EditorGUILayout.ToggleLeft(caption, ruleEnabled);
            GUI.enabled = ruleEnabled;
            MonoScript script = null;

            if (ruleClassName != null)
            {
                var rule = instanceCache.GetInstance(ruleClassName) as ScriptableObject;
                if (rule != null)
                {
                    script = MonoScript.FromScriptableObject(rule);
                }
            }
            var oldScript = script;

            script = EditorGUILayout.ObjectField(script, typeof(MonoScript), false) as MonoScript;
            if (oldScript != script && script != null)
            {
                ruleClassName = script.GetClass().FullName;
            }
            else if (script == null)
            {
                ruleClassName = null;
            }

            EditorGUILayout.EndHorizontal();
            GUI.enabled = true;
        }
    //detect is the object that draged is valid
    private static bool IsDragValid()
    {
        //loop through the object is dragged that make sure it is an reaction
        for (int i = 0; i < DragAndDrop.objectReferences.Length; i++)
        {
            //first must be monoscript otherwise invalid
            if (DragAndDrop.objectReferences [i].GetType() != typeof(MonoScript))
            {
                return(false);
            }

            //determine is it a reaction
            MonoScript script = DragAndDrop.objectReferences[i] as MonoScript;
            //find the type of the script
            Type scriptType = script.GetClass();
            //check the typr is not reaction return false
            if (!scriptType.IsSubclassOf(typeof(Reaction)))
            {
                return(false);
            }
            //if the type is abstract alse return false
            if (scriptType.IsAbstract)
            {
                return(false);
            }
        }
        return(true);
    }
Exemplo n.º 18
0
    //Looks through all the objects being dragged and checks that they (all) inherit from Action
    private static bool IsDragValid()
    {
        for (int i = 0; i < DragAndDrop.objectReferences.Length; i++)
        {
            //not a script
            if (DragAndDrop.objectReferences[i].GetType() != typeof(MonoScript))
            {
                return(false);
            }

            MonoScript script     = DragAndDrop.objectReferences[i] as MonoScript;
            Type       scriptType = script.GetClass();

            if (!scriptType.IsSubclassOf(typeof(Action)))
            {
                return(false);
            }

            //Abstracts need their own check
            if (scriptType.IsAbstract)
            {
                return(false);
            }
        }

        return(true);
    }
Exemplo n.º 19
0
 public void OnGUI()
 {
     script = (MonoScript)EditorGUILayout.ObjectField("Type", script, typeof(MonoScript), false);
     if (script)
     {
         var type = script.GetClass();
         // sometimes this happens after code reload
         if (type == null)
         {
             return;
         }
         if (type.canBeUnityComponent())
         {
             if (GUILayout.Button("Select all"))
             {
                 Selection.objects = findObjects(type, true);
             }
             if (GUILayout.Button("Select only exact type"))
             {
                 Selection.objects = findObjects(type, false);
             }
         }
         else
         {
             GUILayout.Label("Type should be MonoBehaviour, Component or interface");
         }
     }
 }
Exemplo n.º 20
0
        private static void DraggingAndDropping(Rect dropArea, ReactionCollectionEditor editor)
        {
            // Cache the current event.
            Event currentEvent = Event.current;

            // If the drop area doesn't contain the mouse then return.
            if (!dropArea.Contains(currentEvent.mousePosition))
            {
                return;
            }

            switch (currentEvent.type)
            {
            // If the mouse is dragging something...
            case EventType.DragUpdated:

                // ... change whether or not the drag *can* be performed by changing the visual mode of the cursor based on the IsDragValid function.
                DragAndDrop.visualMode = IsDragValid() ? DragAndDropVisualMode.Link : DragAndDropVisualMode.Rejected;

                // Make sure the event isn't used by anything else.
                currentEvent.Use();

                break;

            // If the mouse was dragging something and has released...
            case EventType.DragPerform:

                // ... accept the drag event.
                DragAndDrop.AcceptDrag();

                // Go through all the objects that were being dragged...
                for (int i = 0; i < DragAndDrop.objectReferences.Length; i++)
                {
                    // ... and find the script asset that was being dragged...
                    MonoScript script = DragAndDrop.objectReferences[i] as MonoScript;
                    if (script != null)
                    {
                        // ... then find the type of that Reaction...
                        Type reactionType = script.GetClass();

                        // ... and create a Reaction of that type and add it to the array.
                        Reaction newReaction = ReactionEditor.CreateReaction(reactionType);
                        editor.reactionsProperty.AddToObjectArray(newReaction);
                        continue;
                    }

                    // ... or find the reaction asset that was being dragged...
                    Reaction reaction = DragAndDrop.objectReferences[i] as Reaction;
                    if (reaction != null)
                    {
                        editor.reactionsProperty.AddToObjectArray(reaction);
                    }
                }

                // Make sure the event isn't used by anything else.
                currentEvent.Use();

                break;
            }
        }
Exemplo n.º 21
0
    /// <summary>
    /// Let the user select what king of scriptable object it desires to create and do so
    /// </summary>
    public void OnGUI()
    {
        Setup();

        // Check if we can go directly to the Scriptable Object instance
        if (selectedScriptableTypeIdx == 0)
        {
            MonoScript script = Selection.activeObject as MonoScript;
            if (script != null)
            {
                int idx = typesList.IndexOf(script.GetClass());
                if (idx > 0)
                {
                    selectedScriptableTypeIdx = idx;
                }
            }
        }

        EditorGUILayout.BeginVertical();
        {
            selectedScriptableTypeIdx = EditorGUILayout.Popup(selectedScriptableTypeIdx, names.ToArray <string>());
            EditorGUILayout.Space();

            EditorGUI.BeginDisabledGroup(selectedScriptableTypeIdx == 0);
            if (GUILayout.Button("Enter"))
            {
                ScriptableObjectMenu.CreateItem(typesList[selectedScriptableTypeIdx]);
                Close();
            }
            EditorGUI.EndDisabledGroup();
        }
        EditorGUILayout.EndVertical();
    }
Exemplo n.º 22
0
        // --------------------------------------------------------------
        // Helpers
        // --------------------------------------------------------------

        /// <summary>
        /// Get a list of methods.
        /// </summary>
        /// <param name="monoScript">The script that contains the methods.</param>
        /// <returns>A list of methods.</returns>
        private static List <MethodInfo> AddMethodsToList(MonoScript monoScript)
        {
            // exit early if there is no monoscript
            if (monoScript == null)
            {
                return(new List <MethodInfo>());
            }

            // get the class attached to the monoscript
            System.Type classType = monoScript.GetClass();

            // exit early of there is no class attached to monoscript
            if (classType == null)
            {
                return(new List <MethodInfo>());
            }

            // get the methods attached to the class
            List <MethodInfo> list = new List <MethodInfo>();

            MethodInfo[] methodInfo = classType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
            for (int i = 0; i < methodInfo.Length; i++)
            {
                if (!methodInfo[i].IsSpecialName)
                {
                    list.Add(methodInfo[i]);
                }
            }

            return(list);
        }
Exemplo n.º 23
0
        void Init(MonoScript script)
        {
            m_Initialized = true;
            Type scriptClass = script.GetClass();

            // find public SyncVars to show (user doesn't want protected ones to be shown in inspector)
            foreach (FieldInfo field in scriptClass.GetFields(BindingFlags.Public | BindingFlags.Instance))
            {
                Attribute[] fieldMarkers = (Attribute[])field.GetCustomAttributes(typeof(SyncVarAttribute), true);
                if (fieldMarkers.Length > 0)
                {
                    m_SyncVarNames.Add(field.Name);
                }
            }

            int numSyncLists = scriptClass.GetFields().Count(
                field => field.FieldType.BaseType != null &&
                field.FieldType.BaseType.Name.Contains("SyncList"));

            if (numSyncLists > 0)
            {
                m_ShowSyncLists = new bool[numSyncLists];
            }

            m_SyncsAnything = SyncsAnything(scriptClass);
        }
Exemplo n.º 24
0
    public override void OnInspectorGUI()
    {
        if (target == null || !(target is MonoScript))
        {
            return;
        }
        MonoScript script = target as MonoScript;

        System.Type t = script.GetClass();
        if (t == null)
        {
            return;
        }
        if (!(t.IsSubclassOf(typeof(Editor)) || t.IsSubclassOf(typeof(EditorWindow))))
        {
            if (t.IsSubclassOf(typeof(ScriptableObject)) && GUILayout.Button("Create Asset"))
            {
                ScriptableObjectUtility.CreateAsset(t);
            }
        }

        showCode = EditorGUILayout.Foldout(showCode, "Code");
        if (showCode)
        {
            EditorGUILayout.TextArea(script.text);
        }
    }
Exemplo n.º 25
0
        /// <summary>
        ///     Determines if the script is a singleton scriptable object.
        /// </summary>
        /// <returns><c>true</c> if is singleton; otherwise, <c>false</c>.</returns>
        /// <param name="script">Script.</param>
        private static bool IsSingleton(MonoScript script)
        {
            Type toCheck = script.GetClass();
            Type generic = typeof(SingletonHydraScriptableObject <>);

            return(ReflectionUtils.IsSubclassOfRawGeneric(generic, toCheck));
        }
Exemplo n.º 26
0
        private bool IsValidImport(object[] objects)
        {
            if (objects.Length == 0)
            {
                return(false);
            }

            for (int i = 0; i < objects.Length; i++)
            {
                object importObject = objects[i];

                if (importObject.GetType() == typeof(MonoScript))
                {
                    MonoScript monoScriptImport = (MonoScript)importObject;

                    Type monoScriptType = monoScriptImport.GetClass();
                    if (monoScriptType == null ||
                        !typeof(BehaviourNode).IsAssignableFrom(monoScriptType))
                    {
                        return(false);
                    }
                }
                else if (!typeof(IBehaviourGraph).IsAssignableFrom(importObject.GetType()))
                {
                    return(false);
                }
            }
            return(true);
        }
        private void OnEnable()
        {
            MonoScript script = (MonoScript)target;

            m_type = script.GetClass();
            m_isScriptableObject = IsScriptableObject(m_type);
        }
Exemplo n.º 28
0
        public static void CreateAssetFromSelectedScript()
        {
            MonoScript script = Selection.objects[0] as MonoScript;
            string     path;

            if (IsSingleton(script))
            {
                path = GetSingletonPath(script);
            }
            else
            {
                path = EditorUtility.SaveFilePanel("Save location", "Assets", "New " + script.name, "asset");
            }

            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            // Get project relative path and ensure path is within project
            string projectRelative = FileUtil.GetProjectRelativePath(path);

            if (string.IsNullOrEmpty(projectRelative))
            {
                EditorUtility.DisplayDialog("Error", "Please select somewhere within your assets folder.", "OK");
                return;
            }

            CreateAsset(script.GetClass(), path);
        }
Exemplo n.º 29
0
        private void ProcessSourceFile(string sourceFile, string sourceIncludeTemplate, List <string> sourceIncludes, Dictionary <string, string> sourceGuidToClassName)
        {
            // Get the entry for the map
            string     guid           = AssetDatabase.AssetPathToGUID(sourceFile);
            MonoScript asset          = AssetDatabase.LoadAssetAtPath <MonoScript>(sourceFile);
            string     classNameToAdd = null;

            if (asset != null)
            {
                classNameToAdd = asset.GetClass()?.FullName;
            }

            sourceGuidToClassName.Add(guid, classNameToAdd);

            string normalized = Utilities.GetNormalizedPath(sourceFile);

            if (normalized.StartsWith("Packages"))
            {
                normalized = "PackagesCopy" + normalized.Substring("Packages".Length);
            }

            string sourcePath = normalized;

            if (sourcePath.StartsWith("Assets"))
            {
                sourcePath = "..\\" + sourcePath;
            }

            sourceIncludes.Add(Utilities.ReplaceTokens(sourceIncludeTemplate, new Dictionary <string, string>()
            {
                { "##RELATIVE_SOURCE_PATH##", $"..\\{sourcePath}" },
                { "##PROJECT_LINK_PATH##", normalized.Replace("Assets\\", string.Empty) }
            }));
        }
        public static void DisableGizmoIcon(MonoScript script)
        {
            //----Doesnt Work----//
            Type AnnotationUtility = Type.GetType("UnityEditor.AnnotationUtility, UnityEditor");
            var  scriptClass       = script.GetClass();

            MethodInfo getAnnotations  = AnnotationUtility.GetMethod("GetAnnotations", BindingFlags.Static | BindingFlags.NonPublic);
            MethodInfo setIconEnabled  = AnnotationUtility.GetMethod("SetIconEnabled", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
            MethodInfo setGizmoEnabled = AnnotationUtility.GetMethod("SetGizmoEnabled", BindingFlags.Static | BindingFlags.NonPublic);

            var annotations = getAnnotations.Invoke(null, null);

            foreach (object annotation in (IEnumerable)annotations)
            {
                Type      annotationType   = annotation.GetType();
                FieldInfo classIdField     = annotationType.GetField("classID", BindingFlags.Public | BindingFlags.Instance);
                FieldInfo scriptClassField = annotationType.GetField("scriptClass", BindingFlags.Public | BindingFlags.Instance);
                if (classIdField != null && scriptClassField != null)
                {
                    //int classId = (int)classIdField.GetValue(annotation);
                    string _scriptClass = (string)scriptClassField.GetValue(annotation);
                    if (_scriptClass == scriptClass.Name)
                    {
                        Debug.Log(_scriptClass);
                        int classId = (int)classIdField.GetValue(annotation);
                        setIconEnabled.Invoke(null, new object[] { classId, _scriptClass, 0 });
                    }
                }
            }
        }