//[InitializeOnLoadMethod]
        public static void RemoveObsoleteGeneratedOdinEditorsDLL_InitializeOnLoadMethod()
        {
            EditorApplication.delayCall += () =>
            {
                EditorApplication.delayCall += () =>
                {
#if SIRENIX_INTERNAL
                    if (AssemblyUtilities.GetTypeByCachedFullName("Sirenix.Internal.SirenixProduct") != null)
                    {
                        return;
                    }
#endif
                    if (EditorPrefs.HasKey("PREVENT_SIRENIX_FILE_GENERATION"))
                    {
                        return;
                    }

                    var generatedOdinEditorsFolder = "Assets/" + SirenixAssetPaths.SirenixAssembliesPath + "Editor";
                    var generatedOdinEditorsDLL    = generatedOdinEditorsFolder + "/GeneratedOdinEditors.dll";

                    if (File.Exists(generatedOdinEditorsDLL))
                    {
                        AssetDatabase.DeleteAsset(generatedOdinEditorsDLL);
                        if (File.Exists(generatedOdinEditorsDLL + ".mdb"))
                        {
                            AssetDatabase.DeleteAsset(generatedOdinEditorsDLL + ".mdb");
                        }

                        AssetDatabase.Refresh();
                    }
                };
            };
        }
Esempio n. 2
0
        static AnimationCurveDrawer()
        {
            MethodInfo mi   = null;
            var        type = AssemblyUtilities.GetTypeByCachedFullName("UnityEditorInternal.AnimationCurvePreviewCache");

            if (type != null)
            {
                var method = type.GetMethod("ClearCache", Flags.StaticAnyVisibility);
                var pars   = method.GetParameters();
                if (pars != null && pars.Length == 0)
                {
                    mi = method;
                }
            }

            if (mi != null)
            {
                clearCache = EmitUtilities.CreateStaticMethodCaller(mi);
            }
#if SIRENIX_INTERNAL
            else
            {
                Debug.LogError("AnimationCurve fix no longer works, has Unity fixed it?");
            }
#endif
        }
Esempio n. 3
0
        internal static void OpenEditorInOdinDropDown(UnityEngine.Object obj, Rect btnRect)
        {
            var odinEditorWindow = AssemblyUtilities.GetTypeByCachedFullName("Sirenix.OdinInspector.Editor.OdinEditorWindow");

            odinEditorWindow.GetMethods(Flags.StaticPublic)
            .First(x => x.Name == "InspectObjectInDropDown" && x.GetParameters().Last().ParameterType == typeof(float))
            .Invoke(null, new object[] { obj, btnRect, 400 });
        }
Esempio n. 4
0
        /// <summary>
        /// Binds a name to type.
        /// </summary>
        /// <param name="typeName">The name of the type to bind.</param>
        /// <param name="debugContext">The debug context to log to.</param>
        /// <returns>
        /// The type that the name has been bound to, or null if the type could not be resolved.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">The typeName argument is null.</exception>
        public override Type BindToType(string typeName, DebugContext debugContext = null)
        {
            if (typeName == null)
            {
                throw new ArgumentNullException("typeName");
            }

            Type result;

            lock (TYPEMAP_LOCK)
            {
                if (typeMap.TryGetValue(typeName, out result) == false)
                {
                    // Looks for custom defined type name lookups defined with the BindTypeNameToTypeAttribute.
                    customTypeNameToTypeBindings.TryGetValue(typeName, out result);

                    // Do more fancy stuff.

                    // Final fallback to classic .NET type string format
                    if (result == null)
                    {
                        result = Type.GetType(typeName);
                    }

                    if (result == null)
                    {
                        result = AssemblyUtilities.GetTypeByCachedFullName(typeName);
                    }

                    // TODO: Type lookup error handling; use an out bool or a "Try" pattern?

                    string typeStr, assemblyStr;

                    ParseName(typeName, out typeStr, out assemblyStr);

                    if (result == null && assemblyStr != null && assemblyNameLookUp.ContainsKey(assemblyStr))
                    {
                        var assembly = assemblyNameLookUp[assemblyStr];
                        result = assembly.GetType(typeStr);
                    }

                    if (result == null)
                    {
                        result = AssemblyUtilities.GetTypeByCachedFullName(typeStr);
                    }

                    if (result == null && debugContext != null)
                    {
                        debugContext.LogWarning("Failed deserialization type lookup for type name '" + typeName + "'.");
                    }

                    // We allow null values on purpose so we don't have to keep re-performing invalid name lookups
                    typeMap.Add(typeName, result);
                }
            }

            return(result);
        }
        static UnityNetworkingUtility()
        {
            NetworkBehaviourType = AssemblyUtilities.GetTypeByCachedFullName("UnityEngine.Networking.NetworkBehaviour");
            SyncListType         = AssemblyUtilities.GetTypeByCachedFullName("UnityEngine.Networking.SyncList`1");

            if (NetworkBehaviourType != null)
            {
                getNetworkChannelMethod  = DeepReflection.CreateWeakInstanceValueGetter <int>(NetworkBehaviourType, "GetNetworkChannel()");
                getNetworkIntervalMethod = DeepReflection.CreateWeakInstanceValueGetter <float>(NetworkBehaviourType, "GetNetworkSendInterval()");
            }
        }
        private Type ParseTypeName(string typeName, DebugContext debugContext)
        {
            Type type;

            // Look for custom defined type name lookups defined with the BindTypeNameToTypeAttribute.
            if (customTypeNameToTypeBindings.TryGetValue(typeName, out type))
            {
                return(type);
            }

            // Let's try it the traditional .NET way
            type = Type.GetType(typeName);
            if (type != null)
            {
                return(type);
            }

            // Let's try a short-cut
            type = AssemblyUtilities.GetTypeByCachedFullName(typeName);
            if (type != null)
            {
                return(type);
            }

            // Generic/array type name handling
            type = ParseGenericAndOrArrayType(typeName, debugContext);
            if (type != null)
            {
                return(type);
            }

            string typeStr, assemblyStr;

            ParseName(typeName, out typeStr, out assemblyStr);

            if (assemblyStr != null && assemblyNameLookUp.ContainsKey(assemblyStr))
            {
                var assembly = assemblyNameLookUp[assemblyStr];
                type = assembly.GetType(typeStr);
                if (type != null)
                {
                    return(type);
                }
            }

            type = AssemblyUtilities.GetTypeByCachedFullName(typeStr);
            if (type != null)
            {
                return(type);
            }

            return(null);
        }
        protected internal static Type GetTypeFromString(string typeString)
        {
            Type type = Binder.BindToType(typeString);

            if (type == null)
            {
                type = AssemblyUtilities.GetTypeByCachedFullName(typeString);
            }

            if (type == null)
            {
                ExpressionUtility.TryParseTypeNameAsCSharpIdentifier(typeString, out type);
            }

            return(type);
        }
            private void OpenEditorWindow()
            {
                var type = AssemblyUtilities.GetTypeByCachedFullName(this.StringValue);

                if (type != null)
                {
                    if (type.InheritsFrom <UnityEditor.EditorWindow>())
                    {
                        var window = EditorWindow.GetWindow(type);
                        window.position = GUIHelper.GetEditorWindowRect().AlignCenter(windowSize.x, windowSize.y);
                    }
                    else
                    {
                        var window = OdinEditorWindow.InspectObject(Activator.CreateInstance(type));
                        window.position = GUIHelper.GetEditorWindowRect().AlignCenter(windowSize.x, windowSize.y);
                    }
                }
                else if (File.Exists(this.StringValue))
                {
                    var obj    = AssetDatabase.LoadAssetAtPath(this.StringValue, typeof(UnityEngine.Object));
                    var window = OdinEditorWindow.InspectObject(obj);
                    window.position = GUIHelper.GetEditorWindowRect().AlignCenter(windowSize.x, windowSize.y);
                }
            }
Esempio n. 9
0
        /// <summary>
        /// Draws the property.
        /// </summary>
        protected override void DrawPropertyLayout(IPropertyValueEntry <T> entry, GUIContent label)
        {
            Context context;

            if (entry.Context.Get(this, "context", out context))
            {
                context.UniqueControlName = Guid.NewGuid().ToString();
            }

            if (!context.IsValid)
            {
                GUIHelper.PushColor(Color.red);
            }

            GUI.SetNextControlName(context.UniqueControlName);

            Rect rect = EditorGUILayout.GetControlRect();

            if (label != null)
            {
                rect = EditorGUI.PrefixLabel(rect, label);
            }

            Rect fieldRect    = rect;
            Rect dropdownRect = rect.AlignRight(18);

            // Dropdown button.
            EditorGUIUtility.AddCursorRect(dropdownRect, MouseCursor.Arrow);
            if (GUI.Button(dropdownRect, GUIContent.none, GUIStyle.none))
            {
                TypeSelector selector = new TypeSelector(AssemblyTypeFlags.All, false);

                selector.SelectionConfirmed += t =>
                {
                    var type = t.FirstOrDefault();

                    entry.Property.Tree.DelayAction(() =>
                    {
                        entry.WeakSmartValue = type;
                        context.IsValid      = true;
                        entry.ApplyChanges();
                    });
                };

                selector.SetSelection(entry.SmartValue);
                selector.ShowInPopup(rect, 350);
            }

            // Reset type name.
            if (Event.current.type == EventType.Layout)
            {
                context.TypeNameTemp = entry.SmartValue != null?Binder.BindToName(entry.SmartValue) : null;
            }

            EditorGUI.BeginChangeCheck();
            context.TypeNameTemp = SirenixEditorFields.DelayedTextField(fieldRect, context.TypeNameTemp);

            // Draw dropdown button.
            EditorIcons.TriangleDown.Draw(dropdownRect);

            if (!context.IsValid)
            {
                GUIHelper.PopColor();
            }

            bool isFocused = GUI.GetNameOfFocusedControl() == context.UniqueControlName;
            bool defocused = false;

            if (isFocused != context.WasFocusedControl)
            {
                defocused = !isFocused;
                context.WasFocusedControl = isFocused;
            }

            if (EditorGUI.EndChangeCheck())
            {
                if (string.IsNullOrEmpty(context.TypeNameTemp.Trim()))
                {
                    // String is empty
                    entry.SmartValue = null;
                    context.IsValid  = true;
                }
                else
                {
                    Type type = Binder.BindToType(context.TypeNameTemp);

                    if (type == null)
                    {
                        type = AssemblyUtilities.GetTypeByCachedFullName(context.TypeNameTemp);
                    }

                    if (type == null)
                    {
                        context.IsValid = false;
                    }
                    else
                    {
                        // Use WeakSmartValue in case of a different Type-derived instance showing up somehow, so we don't get cast errors
                        entry.WeakSmartValue = type;
                        context.IsValid      = true;
                    }
                }
            }

            if (defocused)
            {
                // Ensure we show the full type name when the control is defocused
                context.TypeNameTemp = entry.SmartValue == null ? "" : Binder.BindToName(entry.SmartValue);
                context.IsValid      = true;
            }
        }
Esempio n. 10
0
        static InspectorTypeDrawingConfigDrawer()
        {
            NeverDrawTypes = new HashSet <Type>();
            {
                var networkView = AssemblyUtilities.GetTypeByCachedFullName("UnityEngine.NetworkView");
                if (networkView != null)
                {
                    NeverDrawTypes.Add(networkView);
                }
                var gUIText = AssemblyUtilities.GetTypeByCachedFullName("UnityEngine.GUIText");
                if (gUIText != null)
                {
                    NeverDrawTypes.Add(gUIText);
                }
            }

            var unityObjectTypes = AssemblyUtilities.GetTypes(AssemblyTypeFlags.All) // @Tor: Consider switching to AssemblyTypeFlags.CustomTypes?
                                   .Where(type =>
                                          !type.Assembly.IsDynamic() &&
                                          typeof(UnityEngine.Object).IsAssignableFrom(type) &&
                                          //TypeExtensions.IsValidIdentifier(type.FullName) &&
                                          !type.IsDefined <CompilerGeneratedAttribute>() &&
                                          !type.IsDefined <ObsoleteAttribute>() &&
                                          !typeof(Joint).IsAssignableFrom(type) &&
                                          !NeverDrawTypes.Contains(type))
                                   .ToArray();

            Dictionary <Type, Type> haveDrawersAlready     = new Dictionary <Type, Type>();
            Dictionary <Type, Type> derivedClassDrawnTypes = new Dictionary <Type, Type>();

            unityObjectTypes.ForEach(type =>
            {
                if (typeof(Editor).IsAssignableFrom(type))
                {
                    try
                    {
                        bool editorForChildClasses;

                        var drawnType = InspectorTypeDrawingConfig.GetEditorDrawnType(type, out editorForChildClasses);

                        if (drawnType != null)
                        {
                            if (!haveDrawersAlready.ContainsKey(drawnType))
                            {
                                haveDrawersAlready.Add(drawnType, type);
                            }

                            if (editorForChildClasses && !derivedClassDrawnTypes.ContainsKey(drawnType))
                            {
                                derivedClassDrawnTypes.Add(drawnType, type);
                            }
                        }

                        if (/*type.IsVisible && */ InspectorTypeDrawingConfig.UnityInspectorEditorIsValidBase(type, null))
                        {
                            PossibleEditorTypes.Add(type);
                        }
                    }
                    catch (TypeLoadException)
                    {
                    }
                    catch (ReflectionTypeLoadException)
                    {
                    }
                }
            });

            HashSet <Type> stopBaseTypeLookUpTypes = new HashSet <Type>()
            {
                typeof(object),
                typeof(Component),
                typeof(Behaviour),
                typeof(MonoBehaviour),
                typeof(UnityEngine.Object),
                typeof(ScriptableObject),
                typeof(StateMachineBehaviour),
                //typeof(Networking.NetworkBehaviour)
            };

            if (UnityNetworkingUtility.NetworkBehaviourType != null)
            {
                // UnityEngine.Networking has been removed in Unity 2019+.
                stopBaseTypeLookUpTypes.Add(UnityNetworkingUtility.NetworkBehaviourType);
            }

            //Debug.Log("Searching the following " + unityObjectTypes.Length + " types for Odin-drawable types:\n\n" + string.Join("\n", unityObjectTypes.Select(n => n.GetNiceFullName()).ToArray()));

            unityObjectTypes.Where(type => /*type.IsVisible && */ !type.IsAbstract && !type.IsGenericTypeDefinition && !type.IsGenericType && !typeof(Editor).IsAssignableFrom(type) && !typeof(EditorWindow).IsAssignableFrom(type))
            .ForEach(type =>
            {
                Type preExistingEditorType;
                bool haveDrawerAlready = haveDrawersAlready.TryGetValue(type, out preExistingEditorType);

                if (!haveDrawerAlready)
                {
                    Type baseType = type.BaseType;

                    while (baseType != null && !stopBaseTypeLookUpTypes.Contains(baseType))
                    {
                        Type editor;

                        if (derivedClassDrawnTypes.TryGetValue(baseType, out editor))
                        {
                            haveDrawerAlready     = true;
                            preExistingEditorType = editor;
                            break;
                        }

                        baseType = baseType.BaseType;
                    }
                }

                if (!haveDrawerAlready)
                {
                    PossibleDrawnTypes.Add(type);
                }

                AddTypeToGroups(type, preExistingEditorType);
            });

            //Debug.Log("Found the following " + PossibleDrawnTypes.Count + " types that Odin can draw:\n\n" + string.Join("\n", PossibleDrawnTypes.Select(n => n.GetNiceFullName()).ToArray()));

            // Remove editor entries for any types that are not eligible to be drawn
            {
                bool fixedAny = false;

                foreach (var type in InspectorConfig.Instance.DrawingConfig.GetAllDrawnTypesWithEntries())
                {
                    if (!PossibleDrawnTypes.Contains(type))
                    {
                        InspectorConfig.Instance.DrawingConfig.ClearEditorEntryForDrawnType(type);
                        fixedAny = true;
                    }
                }

                if (fixedAny)
                {
                    AssetDatabase.SaveAssets();
                }
            }

            UpdateRootGroupHasEligibletypes();
            UpdateRootGroupConflicts();
            SortRootGroups();
            UpdateRootGroupsSearch("", DisplayType.AllUnityObjects);
        }
            public void Draw()
            {
                bool disable =
                    (this.Type == SectionResourceType.OpenObject && this.UnityObject == null && !File.Exists(this.StringValue)) ||
                    (this.Type == SectionResourceType.Url && string.IsNullOrEmpty(this.StringValue) ||
                     (this.Type == SectionResourceType.OpenEditorWindow && (string.IsNullOrEmpty(this.StringValue) || (AssemblyUtilities.GetTypeByCachedFullName(this.StringValue) == null && !File.Exists(this.StringValue)))));

                GUIHelper.PushGUIEnabled(!disable);

                if (this.HighlightButton && !disable)
                {
                    GUIHelper.PushColor(SirenixGUIStyles.HighlightedButtonColor);
                }

                if (string.IsNullOrEmpty(this.ButtonName))
                {
                    GUILayout.Space(10);
                }
                else
                {
                    if (GUILayout.Button(new GUIContent(" " + ButtonName + " "), GUILayout.Height(19)))
                    {
                        switch (this.Type)
                        {
                        case SectionResourceType.OpenObject:
                            this.OpenObject();
                            break;

                        case SectionResourceType.OpenEditorWindow:
                            this.OpenEditorWindow();
                            break;

                        case SectionResourceType.Url:
                            this.OpenUrl();
                            break;
                        }
                    }
                }

                if (this.HighlightButton && !disable)
                {
                    GUIHelper.PopColor();
                }

                GUIHelper.PopGUIEnabled();
            }
Esempio n. 12
0
        private static void Update()
        {
            bool dontDoIt =
                AssemblyUtilities.GetTypeByCachedFullName("Sirenix.Utilities.Editor.Commands.Command") != null ||
                AssemblyUtilities.GetTypeByCachedFullName("Sirenix.Utilities.Editor.Commands.EditorCommand") != null ||
                EditorPrefs.HasKey("PREVENT_SIRENIX_FILE_GENERATION");

            if (dontDoIt)
            {
                if (DEBUG)
                {
                    Debug.Log(new DirectoryInfo("Assets/" + SirenixAssetPaths.SirenixAssembliesPath).FullName);
                }
                if (DEBUG)
                {
                    Debug.Log("Didn't do it.");
                }
                return;
            }

            if (!File.Exists("Assets/" + SirenixAssetPaths.SirenixPluginPath + "Odin Inspector/Scripts/Editor/OdinUpgrader.cs"))
            {
                if (DEBUG)
                {
                    Debug.Log("The updater doesn't exist, which means the OdinUpgrader was probably just executed and deleted itself, but the program is still in memory.");
                }
                return;
            }

            if (numberOfTimesCalled <= 2)
            {
                // EditorApplication.isCompiling gives an error in 2017 that can't be silenced if called from InitializeOnLoadMethod or DidReloadScripts.
                // We'll just wait a few frames and then call it.
                UnityEditorEventUtility.DelayAction(Update);
                numberOfTimesCalled++;
                return;
            }

            if (counter == NUM_OF_FRAMES_WITHOUT_RECOMPILE)
            {
                if (DEBUG)
                {
                    Debug.Log("Upgrading");
                }
                Upgrade();
            }
            else
            {
                bool isCompiling = true;

                try
                {
                    isCompiling = EditorApplication.isCompiling;
                }
                catch
                {
                }
                finally
                {
                    counter = isCompiling ? 0 : counter + 1;
                }

                if (DEBUG)
                {
                    Debug.Log("Counting " + counter);
                }
                UnityEditorEventUtility.DelayAction(Update);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Draws the property.
        /// </summary>
        protected override void DrawPropertyLayout(IPropertyValueEntry <T> entry, GUIContent label)
        {
            Context context;

            if (entry.Context.Get(this, "context", out context))
            {
                context.uniqueControlName = Guid.NewGuid().ToString();
                context.typeNameTemp      = entry.SmartValue == null ? "" : Binder.BindToName(entry.SmartValue);
            }

            EditorGUI.BeginChangeCheck();

            if (!context.isValid)
            {
                GUIHelper.PushColor(Color.red);
            }

            GUI.SetNextControlName(context.uniqueControlName);

            context.typeNameTemp = SirenixEditorFields.TextField(label, context.typeNameTemp);

            if (!context.isValid)
            {
                GUIHelper.PopColor();
            }

            bool isFocused = GUI.GetNameOfFocusedControl() == context.uniqueControlName;
            bool defocused = false;

            if (isFocused != context.wasFocusedControl)
            {
                defocused = !isFocused;
                context.wasFocusedControl = isFocused;
            }

            if (EditorGUI.EndChangeCheck())
            {
                if (string.IsNullOrEmpty(context.typeNameTemp.Trim()))
                {
                    // String is empty
                    entry.SmartValue = null;
                    context.isValid  = true;
                }
                else
                {
                    Type type = Binder.BindToType(context.typeNameTemp);

                    if (type == null)
                    {
                        type = AssemblyUtilities.GetTypeByCachedFullName(context.typeNameTemp);
                    }

                    if (type == null)
                    {
                        context.isValid = false;
                    }
                    else
                    {
                        // Use WeakSmartValue in case of a different Type-derived instance showing up somehow, so we don't get cast errors
                        entry.WeakSmartValue = type;
                        context.isValid      = true;
                    }
                }
            }

            if (defocused)
            {
                // Ensure we show the full type name when the control is defocused
                context.typeNameTemp = entry.SmartValue == null ? "" : Binder.BindToName(entry.SmartValue);
                context.isValid      = true;
            }
        }