GetClass() private method

private GetClass ( ) : Type
return System.Type
示例#1
0
    private static void ProcessManagerAttributes()
    {
        var types = new string[] { ".cs", ".js" };

        var allScriptPaths = Directory.GetFiles("Assets", "*.*", SearchOption.AllDirectories)
                             .Where(s => types.Any(x => s.EndsWith(x, System.StringComparison.CurrentCultureIgnoreCase)))
                             .ToArray();

        instance.m_attributes.Clear();

        for (int i = 0; i < allScriptPaths.Length; ++i)
        {
            UnityEditor.MonoScript script = UnityEditor.AssetDatabase.LoadAssetAtPath(allScriptPaths[i], typeof(UnityEditor.MonoScript)) as UnityEditor.MonoScript;
            if (!script || script.GetClass() == null)
            {
                continue;
            }
            if (!typeof(Manager).IsAssignableFrom(script.GetClass()))
            {
                continue;
            }

            var type = script.GetClass();
            instance.m_attributes[type] = new ManagerAttributes(type);
        }

        instance.hideFlags = HideFlags.NotEditable;
        UnityEditor.EditorUtility.SetDirty(instance);
        var so = new UnityEditor.SerializedObject(instance);

        so.UpdateIfDirtyOrScript();
        UnityEditor.AssetDatabase.SaveAssets();
    }
示例#2
0
        private void Init(MonoScript script)
        {
            this.m_Initialized              = true;
            this.m_ScriptClass              = script.GetClass();
            this.m_NetworkChannelLabel      = new GUIContent("Network Channel", "QoS channel used for updates. Use the [NetworkSettings] class attribute to change this.");
            this.m_NetworkSendIntervalLabel = new GUIContent("Network Send Interval", "Maximum update rate in seconds. Use the [NetworkSettings] class attribute to change this, or implement GetNetworkSendInterval");
            foreach (System.Reflection.FieldInfo info in this.m_ScriptClass.GetFields(BindingFlags.Public | BindingFlags.Instance))
            {
                Attribute[] customAttributes = (Attribute[])info.GetCustomAttributes(typeof(SyncVarAttribute), true);
                if (customAttributes.Length > 0)
                {
                    this.m_SyncVarNames.Add(info.Name);
                }
            }
            MethodInfo method = script.GetClass().GetMethod("OnSerialize");

            if ((method != null) && (method.DeclaringType != typeof(NetworkBehaviour)))
            {
                this.m_HasOnSerialize = true;
            }
            int num2 = 0;

            foreach (System.Reflection.FieldInfo info3 in base.serializedObject.targetObject.GetType().GetFields())
            {
                if ((info3.FieldType.BaseType != null) && info3.FieldType.BaseType.Name.Contains("SyncList"))
                {
                    num2++;
                }
            }
            if (num2 > 0)
            {
                this.m_ShowSyncLists = new bool[num2];
            }
        }
        private void Init(MonoScript script)
        {
            this.m_Initialized              = true;
            this.m_ScriptClass              = script.GetClass();
            this.m_NetworkChannelLabel      = new GUIContent("Network Channel", "QoS channel used for updates. Use the [NetworkSettings] class attribute to change this.");
            this.m_NetworkSendIntervalLabel = new GUIContent("Network Send Interval", "Maximum update rate in seconds. Use the [NetworkSettings] class attribute to change this, or implement GetNetworkSendInterval");
            foreach (System.Reflection.FieldInfo field in this.m_ScriptClass.GetFields(BindingFlags.Instance | BindingFlags.Public))
            {
                if (((Attribute[])field.GetCustomAttributes(typeof(SyncVarAttribute), true)).Length > 0)
                {
                    this.m_SyncVarNames.Add(field.Name);
                }
            }
            MethodInfo method = script.GetClass().GetMethod("OnSerialize");

            if (method != null && method.DeclaringType != typeof(NetworkBehaviour))
            {
                this.m_HasOnSerialize = true;
            }
            int length = 0;

            foreach (System.Reflection.FieldInfo field in this.serializedObject.targetObject.GetType().GetFields())
            {
                if (field.FieldType.BaseType != null && field.FieldType.BaseType.Name.Contains("SyncList"))
                {
                    ++length;
                }
            }
            if (length <= 0)
            {
                return;
            }
            this.m_ShowSyncLists = new bool[length];
        }
示例#4
0
        static bool IsValidScript(MonoScript script)
        {
            if (script == null)
            {
                return(false);
            }

            // The user can only define the order of scripts that contains valid classes (see case 579536)
            if (script.GetClass() == null)
            {
                return(false);
            }

            // Only allow MonoBehaviours and ScriptableObjects
            bool isMonoBehaviour    = typeof(MonoBehaviour).IsAssignableFrom(script.GetClass());
            bool isScriptableObject = typeof(ScriptableObject).IsAssignableFrom(script.GetClass());

            if (!isMonoBehaviour && !isScriptableObject)
            {
                return(false);
            }

            // The user can only define the order of scripts in the assets folder.
            bool isRootFolder, isReadOnly;

            if (!AssetDatabase.GetAssetFolderInfo(AssetDatabase.GetAssetPath(script), out isRootFolder, out isReadOnly))
            {
                return(false);
            }

            return(true);
        }
 private void Init(MonoScript script)
 {
     this.m_Initialized = true;
     this.m_ScriptClass = script.GetClass();
     this.m_NetworkChannelLabel = new GUIContent("Network Channel", "QoS channel used for updates. Use the [NetworkSettings] class attribute to change this.");
     this.m_NetworkSendIntervalLabel = new GUIContent("Network Send Interval", "Maximum update rate in seconds. Use the [NetworkSettings] class attribute to change this, or implement GetNetworkSendInterval");
     foreach (System.Reflection.FieldInfo info in this.m_ScriptClass.GetFields(BindingFlags.Public | BindingFlags.Instance))
     {
         Attribute[] customAttributes = (Attribute[]) info.GetCustomAttributes(typeof(SyncVarAttribute), true);
         if (customAttributes.Length > 0)
         {
             this.m_SyncVarNames.Add(info.Name);
         }
     }
     MethodInfo method = script.GetClass().GetMethod("OnSerialize");
     if ((method != null) && (method.DeclaringType != typeof(NetworkBehaviour)))
     {
         this.m_HasOnSerialize = true;
     }
     int num2 = 0;
     foreach (System.Reflection.FieldInfo info3 in base.serializedObject.targetObject.GetType().GetFields())
     {
         if ((info3.FieldType.BaseType != null) && info3.FieldType.BaseType.Name.Contains("SyncList"))
         {
             num2++;
         }
     }
     if (num2 > 0)
     {
         this.m_ShowSyncLists = new bool[num2];
     }
 }
        private static bool IsValidScript(MonoScript script)
        {
            if (script == null)
            {
                return(false);
            }
            if (script.GetClass() == null)
            {
                return(false);
            }
            bool flag  = typeof(MonoBehaviour).IsAssignableFrom(script.GetClass());
            bool flag2 = typeof(ScriptableObject).IsAssignableFrom(script.GetClass());

            return((flag || flag2) && AssetDatabase.GetAssetPath(script).IndexOf("Assets/") == 0);
        }
    private static void ProcessDependencies()
    {
        ResourceSingletonBuilder.BuildResourceSingletonsIfDirty();

        var so = new UnityEditor.SerializedObject(instance);

        var types = new string[] { ".cs", ".js" };

        var allScriptPaths = Directory.GetFiles("Assets", "*.*", SearchOption.AllDirectories)
                             .Where(s => types.Any(x => s.EndsWith(x, System.StringComparison.CurrentCultureIgnoreCase)))
                             .ToArray();

        instance.m_serializedItems.Clear();

        for (int i = 0; i < allScriptPaths.Length; ++i)
        {
            UnityEditor.MonoScript script = UnityEditor.AssetDatabase.LoadAssetAtPath(allScriptPaths[i], typeof(UnityEditor.MonoScript)) as UnityEditor.MonoScript;

            if (!script || script.GetClass() == null)
            {
                continue;
            }

            var type = script.GetClass();
            if (!typeof(Component).IsAssignableFrom(script.GetClass()) &&
                !typeof(ScriptableObject).IsAssignableFrom(script.GetClass()))
            {
                continue;
            }

            var typeExecutionOrder = UnityEditor.MonoImporter.GetExecutionOrder(script);
            if (typeExecutionOrder == 0)
            {
                continue;
            }

            instance.m_serializedItems.Add(new SerializedItem()
            {
                typeName       = type.FullName,
                executionOrder = typeExecutionOrder,
            });
        }

        so.Update();
        instance.hideFlags = HideFlags.NotEditable;
        UnityEditor.EditorUtility.SetDirty(instance);
        UnityEditor.AssetDatabase.Refresh();
    }
        public override void OnInspectorGUI()
        {
            MonoImporter monoImporter = base.target as MonoImporter;
            MonoScript   script       = monoImporter.GetScript();

            if (script)
            {
                Type @class = script.GetClass();
                if (!InternalEditorUtility.IsInEditorFolder(monoImporter.assetPath))
                {
                    if (!MonoScriptImporterInspector.IsTypeCompatible(@class))
                    {
                        EditorGUILayout.HelpBox("No MonoBehaviour scripts in the file, or their names do not match the file name.", MessageType.Info);
                    }
                }
                List <string>             list  = new List <string>();
                List <UnityEngine.Object> list2 = new List <UnityEngine.Object>();
                bool flag = false;
                using (new EditorGUIUtility.IconSizeScope(new Vector2(16f, 16f)))
                {
                    this.ShowFieldInfo(@class, monoImporter, list, list2, ref flag);
                }
                if (list2.Count != 0)
                {
                    EditorGUILayout.HelpBox("Default references will only be applied in edit mode.", MessageType.Info);
                }
                if (flag)
                {
                    monoImporter.SetDefaultReferences(list.ToArray(), list2.ToArray());
                    AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(monoImporter));
                }
            }
        }
示例#9
0
        public override void OnInspectorGUI()
        {
            MonoImporter target = this.target as MonoImporter;
            MonoScript   script = target.GetScript();

            if (script != null)
            {
                System.Type type = script.GetClass();
                if (!IsTypeCompatible(type))
                {
                    EditorGUILayout.HelpBox("No MonoBehaviour scripts in the file, or their names do not match the file name.", MessageType.Info);
                }
                Vector2 iconSize = EditorGUIUtility.GetIconSize();
                EditorGUIUtility.SetIconSize(new Vector2(16f, 16f));
                List <string>             names   = new List <string>();
                List <UnityEngine.Object> objects = new List <UnityEngine.Object>();
                bool didModify = false;
                this.ShowFieldInfo(type, target, names, objects, ref didModify);
                EditorGUIUtility.SetIconSize(iconSize);
                if (didModify)
                {
                    target.SetDefaultReferences(names.ToArray(), objects.ToArray());
                    AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(target));
                }
            }
        }
示例#10
0
        public void DrawElement(Rect r, object obj, bool dragging)
        {
            MonoScript script = obj as MonoScript;

            if (Event.current.type == EventType.Repaint)
            {
                Styles.elementBackground.Draw(r, false, false, false, false);
                Styles.draggingHandle.Draw(GetDraggingHandleRect(r), false, false, false, false);
            }

            GUI.Label(GetButtonLabelRect(r), script.GetClass().FullName);

            int  oldNr    = GetExecutionOrder(script);
            Rect position = GetFieldRect(r);
            // associate control id with script so that removing an element when its text field is active will not potentially cause subsequent element to inherit value when list is reordered
            int    id     = GUIUtility.GetControlID(script.GetHashCode(), FocusType.Keyboard, position);
            string intStr = EditorGUI.DelayedTextFieldInternal(position, id, GUIContent.none, oldNr.ToString(), "0123456789-", EditorStyles.textField);
            int    newNr  = oldNr;

            if (System.Int32.TryParse(intStr, out newNr) && newNr != oldNr)
            {
                SetExecutionOrder(script, newNr);
                m_Edited = script;
            }

            if (GUI.Button(GetAddRemoveButtonRect(r), Content.iconToolbarMinus, Styles.removeButton))
            {
                SetExecutionOrder(script, 0);
                m_Edited = script;
            }
        }
示例#11
0
        public void DrawElement(Rect r, object obj, bool dragging)
        {
            MonoScript script = obj as MonoScript;

            if (Event.current.type == EventType.Repaint)
            {
                m_Styles.elementBackground.Draw(r, false, false, false, false);
                m_Styles.draggingHandle.Draw(this.GetDraggingHandleRect(r), false, false, false, false);
            }
            GUI.Label(this.GetButtonLabelRect(r), script.GetClass().FullName);
            int    executionOrder = this.GetExecutionOrder(script);
            string s      = EditorGUI.DelayedTextField(this.GetFieldRect(r), executionOrder.ToString(), "0123456789-", EditorStyles.textField);
            int    result = executionOrder;

            if (int.TryParse(s, out result) && (result != executionOrder))
            {
                this.SetExecutionOrder(script, result);
                this.m_Edited = script;
            }
            if (GUI.Button(this.GetAddRemoveButtonRect(r), m_Styles.iconToolbarMinus, m_Styles.removeButton))
            {
                this.SetExecutionOrder(script, 0);
                this.m_Edited = script;
            }
        }
示例#12
0
    static Type[] GetScriptDependencies(UnityEditor.MonoScript script)
    {
        if (script == null)
        {
            return(new Type[0]);
        }

        var currentType = script.GetClass();

        if (currentType == null)
        {
            return(new Type[0]);
        }

        Type[] output = null;
        if (!s_dependencyAttributes.TryGetValue(script, out output))
        {
            List <Type> types = new List <Type>();

            var attribs = currentType.GetCustomAttributes(typeof(ScriptDependencyAttribute), true);
            for (int i = 0; i < attribs.Length; ++i)
            {
                var dep = attribs[i] as ScriptDependencyAttribute;
                if (dep == null)
                {
                    continue;
                }
                types.AddRange(dep.GetScriptDependencies()
                               .Where(x => typeof(ScriptableObject).IsAssignableFrom(x) || typeof(MonoBehaviour).IsAssignableFrom(x))
                               );
            }
            s_dependencyAttributes[script] = output = types.ToArray();
        }
        return(output);
    }
        public override void OnInspectorGUI()
        {
            MonoImporter monoImporter = this.target as MonoImporter;
            MonoScript   script       = monoImporter.GetScript();

            if (script)
            {
                Type @class = script.GetClass();
                if (!MonoScriptImporterInspector.IsTypeCompatible(@class))
                {
                    EditorGUILayout.HelpBox("No MonoBehaviour scripts in the file, or their names do not match the file name.", MessageType.Info);
                }
                Vector2 iconSize = EditorGUIUtility.GetIconSize();
                EditorGUIUtility.SetIconSize(new Vector2(16f, 16f));
                List <string>             list  = new List <string>();
                List <UnityEngine.Object> list2 = new List <UnityEngine.Object>();
                bool flag = false;
                this.ShowFieldInfo(@class, monoImporter, list, list2, ref flag);
                EditorGUIUtility.SetIconSize(iconSize);
                if (flag)
                {
                    monoImporter.SetDefaultReferences(list.ToArray(), list2.ToArray());
                    AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(monoImporter));
                }
            }
        }
        public void DrawElement(Rect r, object obj, bool dragging)
        {
            MonoScript monoScript = obj as MonoScript;

            if (Event.current.type == EventType.Repaint)
            {
                ScriptExecutionOrderInspector.m_Styles.elementBackground.Draw(r, false, false, false, false);
                ScriptExecutionOrderInspector.m_Styles.draggingHandle.Draw(this.GetDraggingHandleRect(r), false, false, false, false);
            }
            GUI.Label(this.GetButtonLabelRect(r), monoScript.GetClass().FullName);
            int    executionOrder = this.GetExecutionOrder(monoScript);
            Rect   fieldRect      = this.GetFieldRect(r);
            int    controlID      = GUIUtility.GetControlID(monoScript.GetHashCode(), FocusType.Keyboard, fieldRect);
            string s   = EditorGUI.DelayedTextFieldInternal(fieldRect, controlID, GUIContent.none, executionOrder.ToString(), "0123456789-", EditorStyles.textField);
            int    num = executionOrder;

            if (int.TryParse(s, out num) && num != executionOrder)
            {
                this.SetExecutionOrder(monoScript, num);
                this.m_Edited = monoScript;
            }
            if (GUI.Button(this.GetAddRemoveButtonRect(r), ScriptExecutionOrderInspector.m_Styles.iconToolbarMinus, ScriptExecutionOrderInspector.m_Styles.removeButton))
            {
                this.SetExecutionOrder(monoScript, 0);
                this.m_Edited = monoScript;
            }
        }
示例#15
0
        void Init(MonoScript script)
        {
            m_Initialized = true;
            m_ScriptClass = script.GetClass();

            m_SyncVarIndicatorContent  = new GUIContent("SyncVar", "This variable has been marked with the [SyncVar] attribute.");
            m_NetworkChannelLabel      = new GUIContent("Network Channel", "QoS channel used for updates. Use the [NetworkSettings] class attribute to change this.");
            m_NetworkSendIntervalLabel = new GUIContent("Network Send Interval", "Maximum update rate in seconds. Use the [NetworkSettings] class attribute to change this, or implement GetNetworkSendInterval");

            foreach (var field in m_ScriptClass.GetFields(BindingFlags.Public | BindingFlags.Instance))
            {
                Attribute[] fieldMarkers = (Attribute[])field.GetCustomAttributes(typeof(SyncVarAttribute), true);
                if (fieldMarkers.Length > 0)
                {
                    m_SyncVarNames.Add(field.Name);
                }
            }
            var meth = script.GetClass().GetMethod("OnSerialize");

            if (meth != null)
            {
                if (meth.DeclaringType != typeof(NetworkBehaviour))
                {
                    m_HasOnSerialize = true;
                }
            }

            int numSyncLists = 0;

            foreach (var f in serializedObject.targetObject.GetType().GetFields())
            {
                if (f.FieldType.BaseType != null && f.FieldType.BaseType.Name.Contains("SyncList"))
                {
                    numSyncLists += 1;
                }
            }
            if (numSyncLists > 0)
            {
                m_ShowSyncLists = new bool[numSyncLists];
            }
        }
示例#16
0
        private static bool IsCustomizableScript(MonoScript script)
        {
            bool isCustomizable = false;

            Type scriptClass = script.GetClass();
            if (scriptClass != null)
            {
                isCustomizable = scriptClass.IsSubclassOf(typeof(MonoBehaviour)) || scriptClass.IsSubclassOf(typeof(ScriptableObject));
            }

            return isCustomizable;
        }
    ScriptData Init_Script(UnityEditor.MonoScript script)
    {
        if (script == null)
        {
            throw new System.ArgumentNullException("Init_Script: script cannot be null");
        }

        var scriptClass = script.GetClass();

        if (scriptClass == null)
        {
            throw new System.ArgumentNullException("Init_Script: must be a monoscript with a valid class");
        }

        ScriptData scriptData = null;

        if (scriptDataTable.TryGetValue(script, out scriptData))
        {
            return(scriptData);
        }
        else
        {
            scriptData        = scriptDataTable[script] = new ScriptData();
            scriptData.script = script;
        }


        var fixedOrderAttribute = scriptClass.GetCustomAttributes(typeof(ScriptExecutionOrderAttribute), true).Cast <ScriptExecutionOrderAttribute>().FirstOrDefault();

        if (fixedOrderAttribute != null)
        {
            scriptData.fixedOrderValue = fixedOrderAttribute.order;
        }
        var dependsOnAttributes = scriptClass.GetCustomAttributes(typeof(ScriptDependencyAttribute), true).Cast <ScriptDependencyAttribute>().ToArray();

        foreach (var i in dependsOnAttributes)
        {
            var dependsOnTypes = i.GetScriptDependencies()
                                 .Where(x => typeLookup.ContainsKey(x))
                                 .Select(x => typeLookup[x])
                                 .ToArray();

            foreach (var j in dependsOnTypes)
            {
                var dependsOnSD = Init_Script(j);
                dependsOnSD.dependedOnBy.Add(scriptData);
                scriptData.dependsOn.Add(dependsOnSD);
            }
        }

        return(scriptData);
    }
    static Type[] GetScriptDependencies(UnityEditor.MonoScript script)
    {
        if (script == null)
        {
            return(new Type[0]);
        }

        var currentType = script.GetClass();

        if (currentType == null)
        {
            return(new Type[0]);
        }

        if (s_compatibleTypes == null)
        {
            var scriptsToSort = MonoImporter.GetAllRuntimeMonoScripts()
                                .Select(x => x.GetClass())
                                .Where(x => x != null)
                                .Distinct()
                                .ToArray();

            s_compatibleTypes = scriptsToSort.ToDictionary(
                x => x,
                x => scriptsToSort.Where(x.IsAssignableFrom).ToArray());
        }

        Type[] output = null;
        if (!s_dependencyAttributes.TryGetValue(script, out output))
        {
            HashSet <Type> types = new HashSet <Type>();

            var attribs = currentType.GetCustomAttributes(typeof(ScriptDependencyAttribute), true);
            for (int i = 0; i < attribs.Length; ++i)
            {
                var dep = attribs[i] as ScriptDependencyAttribute;
                if (dep == null)
                {
                    continue;
                }

                foreach (var depType in dep.GetScriptDependencies())
                {
                    types.UnionWith(s_compatibleTypes[depType]);
                }
            }
            s_dependencyAttributes[script] = output = types.ToArray();
        }
        return(output);
    }
        private static bool IsValidScript(MonoScript script)
        {
            if (script == null)
            {
                return(false);
            }
            if (script.GetClass() == null)
            {
                return(false);
            }
            bool flag2 = typeof(MonoBehaviour).IsAssignableFrom(script.GetClass());
            bool flag3 = typeof(ScriptableObject).IsAssignableFrom(script.GetClass());

            if (!flag2 && !flag3)
            {
                return(false);
            }
            if (AssetDatabase.GetAssetPath(script).IndexOf("Assets/") != 0)
            {
                return(false);
            }
            return(true);
        }
    private static void ProcessDependencies()
    {
        ResourceSingletonBuilder.BuildResourceSingletonsIfDirty();

        var types = new string[] { ".cs", ".js" };

        var allScriptPaths = Directory.GetFiles("Assets", "*.*", SearchOption.AllDirectories)
                             .Where(s => types.Any(x => s.EndsWith(x, System.StringComparison.CurrentCultureIgnoreCase)))
                             .ToArray();

        for (int i = 0; i < allScriptPaths.Length; ++i)
        {
            UnityEditor.MonoScript script = UnityEditor.AssetDatabase.LoadAssetAtPath(allScriptPaths[i], typeof(UnityEditor.MonoScript)) as UnityEditor.MonoScript;
            if (!script || script.GetClass() == null)
            {
                continue;
            }
            if (!typeof(Component).IsAssignableFrom(script.GetClass()))
            {
                continue;
            }

            var type       = script.GetClass();
            var attributes = (ComponentDependencyAttribute[])type.GetCustomAttributes(typeof(ComponentDependencyAttribute), true);
            if (attributes.Length == 0)
            {
                continue;
            }

            var dependencies = attributes
                               .Where(x => x != null)
                               .SelectMany(x => x.GetComponentDependencies())
                               .ToArray();

            ProcessAll_SetDependencies(type, dependencies);
        }
    }
示例#21
0
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (Application.isPlaying)
            return;

        MCP_AI.Environment myTarget = (MCP_AI.Environment)target;
        myTarget.AttackerControllerType =(MCP_AI.AgentAI.OPTIONS)EditorGUILayout.EnumPopup("Attacker Controller Type",myTarget.AttackerControllerType);
        if (myTarget.AttackerControllerType == MCP_AI.AgentAI.OPTIONS.CustomAI)
        {
            aS = EditorGUILayout.ObjectField("Controller Class", aS, typeof(MonoScript), false) as MonoScript;
            if (aS != null && aS.GetClass().BaseType.Equals(typeof(MCP_AI.AIController)))
            {
                myTarget.AttackController = aS.GetClass().Name;
            }
        }
        else
        {
            myTarget.AttackController = GetClassName(myTarget.AttackerControllerType, null);
        }

        myTarget.DefenderControllerType = (MCP_AI.AgentAI.OPTIONS)EditorGUILayout.EnumPopup("Defender Controller Type", myTarget.DefenderControllerType);
        if (myTarget.DefenderControllerType == MCP_AI.AgentAI.OPTIONS.CustomAI)
        {
            dS = EditorGUILayout.ObjectField("Controller Class", dS, typeof(MonoScript), false) as MonoScript;
            if (dS != null && dS.GetClass().BaseType.Equals(typeof(MCP_AI.AIController)))
            {

                myTarget.DefendController = dS.GetClass().Name;
            }
        }
        else
        {
            myTarget.DefendController = GetClassName(myTarget.DefenderControllerType, null);
        }
    }
 private void Init(MonoScript script)
 {
   this.m_Initialized = true;
   this.m_ScriptClass = script.GetClass();
   this.m_NetworkChannelLabel = new GUIContent("Network Channel", "QoS channel used for updates. Use the [NetworkSettings] class attribute to change this.");
   this.m_NetworkSendIntervalLabel = new GUIContent("Network Send Interval", "Maximum update rate in seconds. Use the [NetworkSettings] class attribute to change this, or implement GetNetworkSendInterval");
   foreach (System.Reflection.FieldInfo field in this.m_ScriptClass.GetFields(BindingFlags.Instance | BindingFlags.Public))
   {
     if (((Attribute[]) field.GetCustomAttributes(typeof (SyncVarAttribute), true)).Length > 0)
       this.m_SyncVarNames.Add(field.Name);
   }
   MethodInfo method = script.GetClass().GetMethod("OnSerialize");
   if (method != null && method.DeclaringType != typeof (NetworkBehaviour))
     this.m_HasOnSerialize = true;
   int length = 0;
   foreach (System.Reflection.FieldInfo field in this.serializedObject.targetObject.GetType().GetFields())
   {
     if (field.FieldType.BaseType != null && field.FieldType.BaseType.Name.Contains("SyncList"))
       ++length;
   }
   if (length <= 0)
     return;
   this.m_ShowSyncLists = new bool[length];
 }
        /// <summary> Automatically delete Node sub-assets before deleting their script.
        /// This is important to do, because you can't delete null sub assets.
        /// <para/> For another workaround, see: https://gitlab.com/RotaryHeart-UnityShare/subassetmissingscriptdelete </summary>
        private static AssetDeleteResult OnWillDeleteAsset(string path, RemoveAssetOptions options)
        {
            // Skip processing anything without the .cs extension
            if (Path.GetExtension(path) != ".cs")
            {
                return(AssetDeleteResult.DidNotDelete);
            }

            // Get the object that is requested for deletion
            UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(path);

            // If we aren't deleting a script, return
            if (!(obj is UnityEditor.MonoScript))
            {
                return(AssetDeleteResult.DidNotDelete);
            }

            // Check script type. Return if deleting a non-node script
            UnityEditor.MonoScript script     = obj as UnityEditor.MonoScript;
            System.Type            scriptType = script.GetClass();
            if (scriptType == null || (scriptType != typeof(XNode.Node) && !scriptType.IsSubclassOf(typeof(XNode.Node))))
            {
                return(AssetDeleteResult.DidNotDelete);
            }

            // Find all ScriptableObjects using this script
            string[] guids = AssetDatabase.FindAssets("t:" + scriptType);
            for (int i = 0; i < guids.Length; i++)
            {
                string   assetpath = AssetDatabase.GUIDToAssetPath(guids[i]);
                Object[] objs      = AssetDatabase.LoadAllAssetRepresentationsAtPath(assetpath);
                for (int k = 0; k < objs.Length; k++)
                {
                    XNode.Node node = objs[k] as XNode.Node;
                    if (node.GetType() == scriptType)
                    {
                        if (node != null && node.graph != null)
                        {
                            // Delete the node and notify the user
                            Debug.LogWarning(node.name + " of " + node.graph + " depended on deleted script and has been removed automatically.", node.graph);
                            node.graph.RemoveNode(node);
                        }
                    }
                }
            }
            // We didn't actually delete the script. Tell the internal system to carry on with normal deletion procedure
            return(AssetDeleteResult.DidNotDelete);
        }
        private void Init(MonoScript script)
        {
            initialized = true;

            syncedVarLabelGuiContent = new GUIContent("SyncedVar", "This variable has been marked with the [SyncedVar] attribute.");

            FieldInfo[] fields = script.GetClass().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic);
            for (int i = 0; i < fields.Length; i++)
            {
                Attribute[] attributes = (Attribute[])fields[i].GetCustomAttributes(typeof(SyncedVar), true);
                if (attributes.Length > 0)
                {
                    syncedVarNames.Add(fields[i].Name);
                }
            }
        }
示例#25
0
        static bool HasValidScript(UnityEngine.Object obj)
        {
            MonoScript script = MonoScript.FromScriptedObject(obj);

            if (script == null)
            {
                return(false);
            }
            Type type = script.GetClass();

            if (type == null)
            {
                return(false);
            }
            return(true);
        }
        private static System.Type GetScriptTypeFromProperty(SerializedProperty property)
        {
            SerializedProperty property1 = property.serializedObject.FindProperty("m_Script");

            if (property1 == null)
            {
                return((System.Type)null);
            }
            MonoScript objectReferenceValue = property1.objectReferenceValue as MonoScript;

            if ((UnityEngine.Object)objectReferenceValue == (UnityEngine.Object)null)
            {
                return((System.Type)null);
            }
            return(objectReferenceValue.GetClass());
        }
示例#27
0
    void OnValidate()
    {
#if UNITY_EDITOR
        if (script != null)
        {
            UnityEditor.MonoScript monoscript = (UnityEditor.MonoScript)script;

            if (monoscript == null)
            {
                throw new InvalidOperationException("Text asset is not a valid Monoscript");
            }

            stateClassFullName = monoscript.GetClass().FullName;
        }
#endif
    }
示例#28
0
        private static Type GetScriptTypeFromProperty(SerializedProperty property)
        {
            SerializedProperty serializedProperty = property.serializedObject.FindProperty("m_Script");

            if (serializedProperty == null)
            {
                return(null);
            }
            MonoScript monoScript = serializedProperty.objectReferenceValue as MonoScript;

            if (monoScript == null)
            {
                return(null);
            }
            return(monoScript.GetClass());
        }
示例#29
0
    private string GetClassName(MCP_AI.AgentAI.OPTIONS option,MonoScript ms)
    {
        switch (option)
        {
            case MCP_AI.AgentAI.OPTIONS.FSMAI:
                return typeof(FSM.FSMAI).Name;

            case MCP_AI.AgentAI.OPTIONS.BTAI:
                return typeof(BT.BTAI).Name;

            case MCP_AI.AgentAI.OPTIONS.RandomAI:
                return typeof(RandomAI).Name;
            case MCP_AI.AgentAI.OPTIONS.CustomAI:
                return ms.GetClass().Name;

        }
        return null;
    }
示例#30
0
        internal static void CopyIconToImporter(MonoScript monoScript)
        {
            // update the icon on the importer (requires a reimport)
            var icon           = EditorGUIUtility.GetIconForObject(monoScript);
            var importer       = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(monoScript));
            var monoImporter   = importer as MonoImporter;
            var pluginImporter = importer as PluginImporter;

            if (monoImporter)
            {
                monoImporter.SetIcon(icon);
                monoImporter.SaveAndReimport();
            }
            else if (pluginImporter)
            {
                pluginImporter.SetIcon(monoScript.GetClass().FullName, icon);
                pluginImporter.SaveAndReimport();
            }
        }
        private void Init(MonoScript script)
        {
            initialized = true;

            networkedVarNames.Clear();
            networkedVarFields.Clear();
            networkedVarObjects.Clear();

            networkedVarLabelGuiContent = new GUIContent("NetworkedVar", "This variable is a NetworkedVar. It can not be serialized and can only be changed during runtime.");

            FieldInfo[] fields = script.GetClass().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy | BindingFlags.NonPublic);
            for (int i = 0; i < fields.Length; i++)
            {
                Type ft = fields[i].FieldType;
                if (ft.IsGenericType && ft.GetGenericTypeDefinition() == typeof(NetworkedVar <>))
                {
                    networkedVarNames.Add(fields[i].Name);
                    networkedVarFields.Add(fields[i].Name, fields[i]);
                }
            }
        }
示例#32
0
        private void Init(MonoScript script)
        {
            m_Initialized = true;

            m_NetworkVariableNames.Clear();
            m_NetworkVariableFields.Clear();
            m_NetworkVariableObjects.Clear();

            m_NetworkVariableLabelGuiContent = new GUIContent("NetworkVariable", "This variable is a NetworkVariable. It can not be serialized and can only be changed during runtime.");

            var fields = script.GetClass().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);

            for (int i = 0; i < fields.Length; i++)
            {
                var ft = fields[i].FieldType;
                if (ft.IsGenericType && ft.GetGenericTypeDefinition() == typeof(NetworkVariable <>) && !fields[i].IsDefined(typeof(HideInInspector), true))
                {
                    m_NetworkVariableNames.Add(fields[i].Name);
                    m_NetworkVariableFields.Add(fields[i].Name, fields[i]);
                }
            }
        }
示例#33
0
        public static AssetDeleteResult OnWillDeleteAsset(string path, RemoveAssetOptions options)
        {
            UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(path);

            if (!(obj is UnityEditor.MonoScript))
            {
                return(AssetDeleteResult.DidNotDelete);
            }

            UnityEditor.MonoScript script     = obj as UnityEditor.MonoScript;
            System.Type            scriptType = script.GetClass();

            if (scriptType != typeof(Node) && !scriptType.IsSubclassOf(typeof(Node)))
            {
                return(AssetDeleteResult.DidNotDelete);
            }

            //Find ScriptableObjects using this script
            string[] guids = AssetDatabase.FindAssets("t:" + scriptType);
            for (int i = 0; i < guids.Length; i++)
            {
                string   assetpath = AssetDatabase.GUIDToAssetPath(guids[i]);
                Object[] objs      = AssetDatabase.LoadAllAssetRepresentationsAtPath(assetpath);
                for (int k = 0; k < objs.Length; k++)
                {
                    Node node = objs[k] as Node;
                    if (node.GetType() == scriptType)
                    {
                        if (node != null && node.graph != null)
                        {
                            Debug.LogWarning(node.name + " of " + node.graph + " depended on deleted script and has been removed automatically.", node.graph);
                            node.graph.RemoveNode(node);
                        }
                    }
                }
            }
            return(AssetDeleteResult.DidNotDelete);
        }
        private static Type GetScriptTypeFromProperty(SerializedProperty property)
        {
            if (property.serializedObject.targetObject != null)
            {
                return(property.serializedObject.targetObject.GetType());
            }

            // Fallback in case the targetObject has been destroyed but the property is still valid.
            SerializedProperty scriptProp = property.serializedObject.FindProperty("m_Script");

            if (scriptProp == null)
            {
                return(null);
            }

            MonoScript script = scriptProp.objectReferenceValue as MonoScript;

            if (script == null)
            {
                return(null);
            }

            return(script.GetClass());
        }
示例#35
0
        private static Object TransformObjectBeingDroppedAccordingToTrackRules(TrackAsset trackToReceiveClip, Object obj)
        {
            Object result;

            if (trackToReceiveClip is PlayableTrack && obj is MonoScript)
            {
                MonoScript monoScript = (MonoScript)obj;
                if (!typeof(IPlayableAsset).IsAssignableFrom(monoScript.GetClass()) || !typeof(Object).IsAssignableFrom(monoScript.GetClass()))
                {
                    Debug.LogError("The MonoScript " + monoScript.get_name() + " is not a valid PlayableAsset");
                    result = null;
                    return(result);
                }
                int num = InternalEditorUtility.CreateScriptableObjectUnchecked(monoScript);
                AssetDatabase.AddInstanceIDToAssetWithRandomFileId(num, trackToReceiveClip, true);
                obj = EditorUtility.InstanceIDToObject(num);
                if (obj == null)
                {
                    Debug.LogError("Unable to create PlayableAsset from MonoScript " + monoScript.get_name());
                }
            }
            result = obj;
            return(result);
        }
		/// <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);
		}
示例#37
0
    void OnGUI()
    {
        Type targetType;
        charScript = AssetDatabase.LoadAssetAtPath<MonoScript>("Assets/Scripts/Enemies/Enemies.cs");
        if (jsonSerializer == null)
        {
            Start();
        }
        targetType = charScript.GetClass();
        EditorGUILayout.BeginVertical(EditorStyles.helpBox);
        EditorGUILayout.LabelField("id: ", database.Count.ToString());

        if (reorderableList == null)
        {
            reorderableList = new ReorderableList(charAbilities, typeof(int),
                false, true, true, true);

            reorderableList.drawElementCallback =
                (Rect rect, int index, bool isActive, bool isFocused) => {
                    var element = reorderableList.list[index];
                    rect.y += 2;
                    reorderableList.list[index] = EditorGUI.IntField(
                        new Rect(rect.x, rect.y, 60, EditorGUIUtility.singleLineHeight),
                        (int)element);
                };
        }
        reorderableList.DoLayoutList();

        foreach (FieldInfo info in targetType.GetFields(flags))
        {
            Type fieldType = info.FieldType;
            if (fieldType == typeof(int))
            {
                info.SetValue(tempEnemy, EditorGUILayout.IntField(info.Name, (int)info.GetValue(tempEnemy)));
            }
            else if (fieldType == typeof(string))
            {
                info.SetValue(tempEnemy, EditorGUILayout.TextField(info.Name, (string)info.GetValue(tempEnemy)));
            }
            else if (fieldType == typeof(float))
            {
                info.SetValue(tempEnemy, EditorGUILayout.FloatField(info.Name, (float)info.GetValue(tempEnemy)));
            }
            else if (fieldType == typeof(Enemies.EnemyStats)) //struct
            {
                EditorGUILayout.Space();
                EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                if (tempStruct == null)
                {
                    tempStruct = new Enemies.EnemyStats();
                    info.SetValue(tempEnemy, (Enemies.EnemyStats)tempStruct);
                }

                foreach (FieldInfo infoInStruct in fieldType.GetFields(flags))
                {
                    Type fieldTypeInStruct = infoInStruct.FieldType;

                    if (fieldTypeInStruct == typeof(float))
                    {
                        infoInStruct.SetValue(tempStruct, EditorGUILayout.FloatField(infoInStruct.Name, (float)infoInStruct.GetValue(info.GetValue(tempEnemy)) ));
                    }
                }

                info.SetValue(tempEnemy, (Enemies.EnemyStats)tempStruct);
                EditorGUILayout.EndVertical();
                EditorGUILayout.Space();
            }
            else if (fieldType == typeof(List<int>))
            {
                info.SetValue(tempEnemy, charAbilities);
            }

        }

        EditorGUILayout.EndVertical();

        if (GUILayout.Button("submit"))
        {
            textWriter = new StreamWriter(Application.dataPath + itemFileName);
            jsonWriter = new JsonTextWriter(textWriter);
            database.Add(tempEnemy);
            String text = JsonConvert.SerializeObject(database, Formatting.Indented, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Objects,
                TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
            });
            textWriter.Write(text);

            textWriter.Close();
            textWriter.Dispose();
            jsonWriter.Close();

            tempEnemy = new Enemies();
            tempStruct = null;
            reorderableList = null;
            charAbilities = new List<int>();
        }
    }
示例#38
0
    void OnGUI()
    {
        Type targetType;
        simpleFood = EditorGUILayout.Toggle("Is Simple Food", simpleFood);
        if (simpleFood)
        {
            mainIngredient = EditorGUILayout.Toggle("Is Main Ingredient", mainIngredient);
            if (mainIngredient)
            {
                itemScript = AssetDatabase.LoadAssetAtPath<MonoScript>("Assets/Scripts/Items/Food/MainIngredient.cs");
                targetType = itemScript.GetClass();
                if (tempItem == null || tempItem.GetType() != targetType)
                {
                    tempItem = new MainIngredient();
                }
            }
            else
            {
                itemScript = AssetDatabase.LoadAssetAtPath<MonoScript>("Assets/Scripts/Items/Food/Accompaniment.cs");
                targetType = itemScript.GetClass();
                if (tempItem == null || tempItem.GetType() != targetType)
                {
                    tempItem = new Accompaniment();
                }
            }
        }
        else
        {
            itemScript = AssetDatabase.LoadAssetAtPath<MonoScript>("Assets/Scripts/Items/Food/ComposedFood.cs");
            targetType = itemScript.GetClass();
            if (tempItem == null || tempItem.GetType() != targetType)
            {
                tempItem = new ComposedFood();
            }

            if (reorderableList == null)
            {
                reorderableList = new ReorderableList(listInputRecipe, typeof(int),
                    false, true, true, true);

                reorderableList.drawElementCallback =
                    (Rect rect, int index, bool isActive, bool isFocused) => {
                        var element = reorderableList.list[index];
                        rect.y += 2;
                        reorderableList.list[index] = EditorGUI.IntField(
                            new Rect(rect.x, rect.y, 60, EditorGUIUtility.singleLineHeight),
                            (int)element);
                    };
            }
            reorderableList.DoLayoutList();
        }

        if (jsonSerializer == null) {
            Start();
        }

        EditorGUILayout.BeginVertical(EditorStyles.helpBox);

        foreach (FieldInfo info in targetType.GetFields(flags))
        {
            Type fieldType = info.FieldType;
            if (fieldType == typeof(int))
            {
                if (info.Name.Contains("id")){
                    info.SetValue(tempItem, database.Count);
                    EditorGUILayout.LabelField("ID of item", database.Count.ToString());
                }
                else
                {
                    info.SetValue(tempItem, EditorGUILayout.IntField(info.Name, (int)info.GetValue(tempItem)));
                }
            }
            else if (fieldType.IsEnum) {
                if (info.GetValue(tempItem) == null)
                    info.SetValue(tempItem, Activator.CreateInstance(fieldType));
                info.SetValue(tempItem, EditorGUILayout.EnumPopup(info.Name, (Enum)info.GetValue(tempItem)));
            }
            else if (fieldType == typeof(string))
            {
                string name = (String)info.GetValue(tempItem);
                info.SetValue(tempItem, EditorGUILayout.TextField(info.Name, name));
            }
            else if (fieldType == typeof(float))
            {
                info.SetValue(tempItem, EditorGUILayout.FloatField(info.Name, (float)info.GetValue(tempItem)));
            }
            else if (fieldType.IsValueType && !fieldType.IsPrimitive && simpleFood) //struct
            {
                EditorGUILayout.Space();
                EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                if (fieldType == typeof(Food.Taste))
                    tempStruct = new Food.Taste();

                foreach (FieldInfo infoInStruct in fieldType.GetFields(flags))
                {
                    Type fieldTypeInStruct = infoInStruct.FieldType;

                    if (fieldTypeInStruct == typeof(int))
                    {
                            infoInStruct.SetValue(tempStruct, EditorGUILayout.IntField(infoInStruct.Name, (int)infoInStruct.GetValue(info.GetValue(tempItem))));
                    }
                }

                if (fieldType == typeof(Food.Taste))
                {
                    info.SetValue(tempItem, (Food.Taste)tempStruct);
                }
                EditorGUILayout.EndVertical();
                EditorGUILayout.Space();
            }
            else if (fieldType == typeof(GameObject))//object
            {
                abilityName = EditorGUILayout.TextField(info.Name, abilityName);
            }
        }

        EditorGUILayout.EndVertical();

        if (GUILayout.Button("submit"))
        {
            textWriter = new StreamWriter(Application.dataPath + itemFileName);
            jsonWriter = new JsonTextWriter(textWriter);
            database.Add(tempItem);
            String text = JsonConvert.SerializeObject(database, Formatting.Indented, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Objects,
                TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
            });
            textWriter.Write(text);

            textWriter.Close();
            textWriter.Dispose();
            jsonWriter.Close();

            if (!simpleFood) {
                tempRecipeStruct = new ComposedFood.recipe(listInputRecipe, tempItem.id);
                textWriter = new StreamWriter(Application.dataPath + recipesFileName);
                jsonWriter = new JsonTextWriter(textWriter);
                recipes.Add((ComposedFood.recipe)tempRecipeStruct);
                String recipeText = JsonConvert.SerializeObject(recipes, Formatting.Indented, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Objects,
                    TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
                });
                textWriter.Write(recipeText);

                textWriter.Close();
                textWriter.Dispose();
                jsonWriter.Close();
            }
            tempItem = null;
            tempStruct = null;
            reorderableList = null;
            listInputRecipe = new List<int>();
        }
    }
    void OnGUI()
    {
        Type targetType;

        if (jsonSerializer == null)
        {
            Start();
        }

        var dirPath = new DirectoryInfo("Assets/Scripts/Abilities/");
        FileInfo[] fileInfo = dirPath.GetFiles();
        List<string> fileNames = new List<string>();
        for(int i = 0; i < fileInfo.Length; i++)
        {
            if (!fileInfo[i].Name.Contains("meta") && !fileInfo[i].Name.Equals("Ability.cs"))
            {
                fileNames.Add(fileInfo[i].Name);
            }
        }
        int newscript = EditorGUILayout.Popup("TasteTranslation:",chosenScript, fileNames.ToArray());
        if(newscript != chosenScript)
        {
            chosenScript = newscript;
            tempAbility = null;
        }
        abilityScript = AssetDatabase.LoadAssetAtPath<MonoScript>("Assets/Scripts/Abilities/"+ fileNames[chosenScript]);
        targetType = abilityScript.GetClass();
        if (tempAbility == null)
        {
            tempAbility = (Ability)Activator.CreateInstance(targetType);
        }
        EditorGUILayout.BeginVertical(EditorStyles.helpBox);
        EditorGUILayout.LabelField("id: ", database.Count.ToString());
        foreach (FieldInfo info in targetType.GetFields(flags))
        {
            Type fieldType = info.FieldType;
            if (fieldType == typeof(int))
            {
                info.SetValue(tempAbility, EditorGUILayout.IntField(info.Name, (int)info.GetValue(tempAbility)));

            }else if(fieldType == typeof(string))
            {
                info.SetValue(tempAbility, EditorGUILayout.TextField(info.Name, (string)info.GetValue(tempAbility)));
            }
            else if (fieldType == typeof(bool))
            {
                info.SetValue(tempAbility, EditorGUILayout.Toggle(info.Name, (bool)info.GetValue(tempAbility)));
            }
        }

        EditorGUILayout.EndVertical();

        if (GUILayout.Button("submit"))
        {
            textWriter = new StreamWriter(Application.dataPath + itemFileName);
            jsonWriter = new JsonTextWriter(textWriter);
            database.Add(tempAbility);
            String text = JsonConvert.SerializeObject(database, Formatting.Indented, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Objects,
                TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
            });
            textWriter.Write(text);

            textWriter.Close();
            textWriter.Dispose();
            jsonWriter.Close();

            tempAbility = null;
        }
    }
示例#40
0
    void OnGUI()
    {
        Type targetType;
        charScript = AssetDatabase.LoadAssetAtPath<MonoScript>("Assets/Scripts/Character/Character.cs");
        if (jsonSerializer == null)
        {
            Start();
        }
        targetType = charScript.GetClass();
        EditorGUILayout.BeginVertical(EditorStyles.helpBox);
        EditorGUILayout.LabelField("id: ", database.Count.ToString());

        if (reorderableList == null)
        {
            reorderableList = new ReorderableList(charAbilities, typeof(int),
                false, true, true, true);

            reorderableList.drawElementCallback =
                (Rect rect, int index, bool isActive, bool isFocused) => {
                    var element = reorderableList.list[index];
                    rect.y += 2;
                    reorderableList.list[index] = EditorGUI.IntField(
                        new Rect(rect.x, rect.y, 60, EditorGUIUtility.singleLineHeight),
                        (int)element);
                };
        }
        reorderableList.DoLayoutList();

        foreach (FieldInfo info in targetType.GetFields(flags))
        {
            Type fieldType = info.FieldType;
            if (fieldType == typeof(int))
            {
                info.SetValue(tempChar, EditorGUILayout.IntField(info.Name, (int)info.GetValue(tempChar)));
            }
            else if (fieldType == typeof(string))
            {
                info.SetValue(tempChar, EditorGUILayout.TextField(info.Name, (string)info.GetValue(tempChar)));
            }
            else if (fieldType == typeof(float))
            {
                info.SetValue(tempChar, EditorGUILayout.FloatField(info.Name, (float)info.GetValue(tempChar)));
            }
            else if (fieldType == typeof(Character.Stats)) //struct
            {
                EditorGUILayout.Space();
                EditorGUILayout.BeginVertical(EditorStyles.helpBox);
                if (tempStruct == null)
                {
                    tempStruct = new Character.Stats();
                    info.SetValue(tempChar, (Character.Stats)tempStruct);
                }

                foreach (FieldInfo infoInStruct in fieldType.GetFields(flags))
                {
                    Type fieldTypeInStruct = infoInStruct.FieldType;

                    if (fieldTypeInStruct == typeof(float))
                    {
                        infoInStruct.SetValue(tempStruct, EditorGUILayout.FloatField(infoInStruct.Name, (float)infoInStruct.GetValue(info.GetValue(tempChar)) ));
                    }
                }

                info.SetValue(tempChar, (Character.Stats)tempStruct);
                EditorGUILayout.EndVertical();
                EditorGUILayout.Space();
            }
            else if (fieldType == typeof(TasteToStats))//object
            {
                var dirPath = new DirectoryInfo("Assets/Scripts/Character/TasteTranslation");
                FileInfo[] fileInfo = dirPath.GetFiles();
                List<string> fileNames = new List<string>();
                for (int i = 0; i < fileInfo.Length; i++)
                {
                    if (!fileInfo[i].Name.Contains("meta") && !fileInfo[i].Name.Equals("TasteToStats.cs"))
                    {
                        fileNames.Add(fileInfo[i].Name);
                    }
                }
                tasteToStats = EditorGUILayout.Popup("Ability:", tasteToStats, fileNames.ToArray());
                MonoScript derp = AssetDatabase.LoadAssetAtPath<MonoScript>("Assets/Scripts/Character/TasteTranslation/"+ fileNames[tasteToStats]);
                info.SetValue(tempChar, Activator.CreateInstance(derp.GetClass()));
            }
            else if (fieldType == typeof(List<int>))
            {
                info.SetValue(tempChar, charAbilities);
            }

        }

        EditorGUILayout.EndVertical();

        if (GUILayout.Button("submit"))
        {
            textWriter = new StreamWriter(Application.dataPath + itemFileName);
            jsonWriter = new JsonTextWriter(textWriter);
            database.Add(tempChar);
            String text = JsonConvert.SerializeObject(database, Formatting.Indented, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Objects,
                TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
            });
            textWriter.Write(text);

            textWriter.Close();
            textWriter.Dispose();
            jsonWriter.Close();

            tempChar = new Character();
            tempStruct = null;
            reorderableList = null;
            charAbilities = new List<int>();
        }
    }
        private void OnGUI()
        {
            const int X = 3;
            const int Height = 20;
            const int Offset = 2;

            int y = 3;
            float width = this.position.width - 2 * X;

            // Show selection field for the user.
            monoScript =
                (MonoScript)
                EditorGUI.ObjectField(
                    new Rect(X, y, width, Height), "Mono Behaviour", monoScript, typeof(MonoScript), false);

            // Show error message if no mono behaviour selected.
            y += Height + Offset;

            if (monoScript == null)
            {
                EditorGUI.LabelField(new Rect(X, y, width, Height), "Missing:", "Select a behaviour first!");
                return;
            }

            if (monoScript.GetClass() == null || !typeof(MonoBehaviour).IsAssignableFrom(monoScript.GetClass()))
            {
                EditorGUI.LabelField(
                    new Rect(X, y, width, Height),
                    "Missing:",
                    string.Format("{0} is no MonoBehaviour.", monoScript.name));
                return;
            }

            // Clear found usages if selection changed.
            if (monoBehaviourType != monoScript.GetClass())
            {
                monoBehaviourType = monoScript.GetClass();
                usages = null;
            }

            // Show Find Usages button.
            if (GUI.Button(new Rect(X, y, width, Height), "Find Prefabs"))
            {
                FindUsages();
            }

            if (usages == null)
            {
                return;
            }

            // Show found usages.
            foreach (GameObject prefab in usages)
            {
                y += Height + Offset;

                EditorGUILayout.BeginHorizontal();

                EditorGUI.LabelField(new Rect(X, y, width / 2, Height), prefab.name);

                if (GUI.Button(new Rect(X + width / 2, y, width / 2, Height), "Navigate To"))
                {
                    NavigateTo(prefab);
                    return;
                }

                EditorGUILayout.EndHorizontal();
            }
        }
 //PRIVATE
 // PUBLIC STATIC
 /// <summary>
 /// Froms the mono script asset.
 /// </summary>
 /// <returns>
 /// The mono script asset.
 /// </returns>
 /// <param name='aCandidate_monoscript'>
 /// A mono script.
 /// </param>
 /// <param name='aInUseScriptableObjects'>
 /// A scriptable objects.
 /// </param>
 /// <param name='aManagers_serializedproperty'>
 /// A managers_serializedproperty.
 /// </param>
 public static UMOMManagerCandidate FromMonoScriptAsset(MonoScript aCandidate_monoscript, List<ScriptableObject> aInUseScriptableObjects, SerializedProperty aManagers_serializedproperty)
 {
     MonoScript monoScriptMatchingCandidate;
     ScriptableObject winningCandidate_scriptableobject = null;
     //FIND THE SCRIPTABLE OBJECT THAT MATCHES THE MONOSCRIPT
     foreach (ScriptableObject scriptableObject in aInUseScriptableObjects) {
         monoScriptMatchingCandidate  = MonoScript.FromScriptableObject (scriptableObject);
         if (monoScriptMatchingCandidate.GetClass().FullName == aCandidate_monoscript.GetClass().FullName) {
             //Debug.Log ("	s: " + monoScriptMatchingCandidate.GetClass().FullName );
             winningCandidate_scriptableobject = scriptableObject;
             break;
         }
     }
     //Debug.Log (" SO : " + winningCandidate_scriptableobject);
     UMOMManagerCandidate managerCandidate = new UMOMManagerCandidate (aCandidate_monoscript, winningCandidate_scriptableobject, aManagers_serializedproperty);
     return managerCandidate;
 }
		public ScriptMatcher( MonoScript script )
		{
			this.script = script;
			this.type = script.GetClass();
			this.fields = GetAllFields( type ).ToList();
		}
		GetNameToPropertyDictionary(MonoScript script)
	{
		List<OCPropertyField> allPropertiesAndFields = new List<OCPropertyField>();

		System.Type currentType = script.GetClass();
//		UnityEngine.Object monoBehaviour = AssetDatabase.GetAllAssetPaths().Select(p => AssetDatabase.LoadAssetAtPath(p, currentType) ).FirstOrDefault();

//		Debug.Log("Step 1");

		if(currentType.IsSubclassOf(typeof(MonoBehaviour)))
		{
					Object[] objects = Resources.FindObjectsOfTypeAll(currentType);

//			Debug.Log("Step 2");

			if(objects.Length != 0)
			{

//				Debug.Log("Step 3");
					allPropertiesAndFields =
						OCPropertyField.GetAllPropertiesAndFields
						( objects[0]
						, null
						, OCExposePropertyFieldsAttribute.OCExposure.PropertiesAndFields
						);
			}
		}

		if(allPropertiesAndFields != null)
			return allPropertiesAndFields.ToDictionary( p => p.PrivateName );
		else
			return null;
	}
    bool CanHaveEditor(MonoScript m)
    {
        if (m.GetClass() == null)
            return false;

        if (m.GetClass().IsSubclassOf(typeof(MonoBehaviour)))
            return true;

        if (m.GetClass().IsSubclassOf(typeof(ScriptableObject)))
        {
            if (!m.GetClass().IsSubclassOf(typeof(Editor)) && !m.GetClass().IsSubclassOf(typeof(EditorWindow)))
                return true;
        }

        return false;
    }
    void DrawField( MonoScript monoScript )
    {
        EditorGUILayout.BeginHorizontal();
        EditorGUILayout.LabelField( monoScript.GetClass().Name );

        if( GUILayout.Button( "Recovery" ) )
        {

            serializedObject.UpdateIfDirtyOrScript();
            serializedObject.FindProperty( "m_Script" ).objectReferenceValue = monoScript;
            serializedObject.ApplyModifiedProperties();

            ActiveEditorTracker.sharedTracker.ForceRebuild();
        }
        EditorGUILayout.EndHorizontal();
    }
		/// <summary>
		/// 	Gets the asset path for the SingletonHydraMonoBehaviour.
		/// </summary>
		/// <returns>The singleton path.</returns>
		/// <param name="script">Script.</param>
		private static string GetSingletonPath(MonoScript script)
		{
			string dataPath = Application.dataPath;
			dataPath = Path.GetDirectoryName(dataPath);

			string local = ReflectionUtils.GetPropertyByName(script.GetClass(), "assetPath").GetValue(null, null) as string;
			return string.Format("{0}/{1}", dataPath, local);
		}