summaryrefslogtreecommitdiff
path: root/Assets/Plugins/Sirenix/Odin Inspector/Scripts/Editor/FixBrokenUnityObjectWrapperDrawer.cs
blob: 1f30e4e2733e1e587cf80ef8bc05870bbc0c38ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
//-----------------------------------------------------------------------
// <copyright file="FixBrokenUnityObjectWrapperDrawer.cs" company="Sirenix IVS">
// Copyright (c) Sirenix IVS. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

#if UNITY_EDITOR && UNITY_2018_3_OR_NEWER
#pragma warning disable

namespace Sirenix.OdinInspector.Editor.Drawers
{
    using Sirenix.OdinInspector;
    using Sirenix.OdinInspector.Editor;
    using Sirenix.Utilities;
    using Sirenix.Utilities.Editor;
    using System.Linq;
    using UnityEditor;
    using UnityEngine;

    [DrawerPriority(0.001, 0, 0)]
    public class FixBrokenUnityObjectWrapperDrawer<T> : OdinValueDrawer<T>, IDefinesGenericMenuItems
        where T : UnityEngine.Component
    {
        private const string AUTO_FIX_PREFS_KEY = "TemporarilyBrokenUnityObjectWrapperDrawer.autoFix";

        private bool isBroken = false;
        private T realWrapperInstance;
        private bool allowSceneViewObjects;
        private static bool autoFix;

        protected override void Initialize()
        {
            this.allowSceneViewObjects = this.ValueEntry.Property.GetAttribute<AssetsOnlyAttribute>() == null;
            autoFix = EditorPrefs.HasKey(AUTO_FIX_PREFS_KEY);
        }

        protected override void DrawPropertyLayout(GUIContent label)
        {
            if (!(this.ValueEntry.ValueState == PropertyValueState.NullReference || this.ValueEntry.ValueState == PropertyValueState.ReferenceValueConflict))
            {
                this.CallNextDrawer(label);
                return;
            }

            if (Event.current.type == EventType.Layout)
            {
                this.isBroken = false;
                var count = this.ValueEntry.ValueCount;
                for (int i = 0; i < count; i++)
                {
                    var component = this.ValueEntry.Values[i];

                    if (ComponentIsBroken(component, ref this.realWrapperInstance))
                    {
                        this.isBroken = true;
                        break;
                    }
                }

                if (this.isBroken && autoFix)
                {
                    this.isBroken = false;

                    for (int i = 0; i < this.ValueEntry.ValueCount; i++)
                    {
                        T fixedComponent = null;
                        if (ComponentIsBroken(this.ValueEntry.Values[i], ref fixedComponent) && fixedComponent)
                        {
                            (this.ValueEntry as IValueEntryActualValueSetter<T>).SetActualValue(i, fixedComponent);
                        }
                    }

                    this.ValueEntry.Update();
                }
            }

            if (!this.isBroken)
            {
                this.CallNextDrawer(label);
                return;
            }

            var rect = EditorGUILayout.GetControlRect(label != null);
            var btnRect = rect.AlignRight(20);
            var controlRect = rect.SetXMax(btnRect.xMin - 5);

            object newInstance = null;

            EditorGUI.BeginChangeCheck();
            {
                if (this.ValueEntry.BaseValueType.IsInterface)
                {
                    newInstance = SirenixEditorFields.PolymorphicObjectField(controlRect,
                        label,
                        this.realWrapperInstance,
                        this.ValueEntry.BaseValueType,
                        this.allowSceneViewObjects);
                }
                else
                {
                    newInstance = SirenixEditorFields.UnityObjectField(
                        controlRect,
                        label,
                        this.realWrapperInstance,
                        this.ValueEntry.BaseValueType,
                        this.allowSceneViewObjects) as Component;
                }
            }
            if (EditorGUI.EndChangeCheck())
            {
                this.ValueEntry.WeakSmartValue = newInstance;
            }

            if (GUI.Button(btnRect, " ", EditorStyles.miniButton))
            {
                var popup = new FixBrokenUnityObjectWrapperPopup(this.ValueEntry);
                OdinEditorWindow.InspectObjectInDropDown(popup, 300);
            }

            if (Event.current.type == EventType.Repaint)
            {
                GUI.DrawTexture(btnRect, EditorIcons.ConsoleWarnicon, ScaleMode.ScaleToFit);
            }
        }

        private static bool ComponentIsBroken(T component, ref T realInstance)
        {
            var uObj = component;
            var oObj = (object)uObj;

            if (oObj != null && uObj == null)
            {
                var instanceId = uObj.GetInstanceID();
                if (AssetDatabase.Contains(instanceId))
                {
                    var path = AssetDatabase.GetAssetPath(instanceId);
                    var realWrapper = AssetDatabase.LoadAllAssetsAtPath(path).FirstOrDefault(n => n.GetInstanceID() == instanceId) as T;
                    if (realWrapper)
                    {
                        realInstance = realWrapper;
                        return true;
                    }
                }
            }

            return false;
        }

        public void PopulateGenericMenu(InspectorProperty property, GenericMenu genericMenu)
        {
            if (EditorPrefs.HasKey(AUTO_FIX_PREFS_KEY))
            {
                genericMenu.AddItem(new GUIContent("Disable auto-fix of broken prefab instance references"), false, (x) =>
                {
                    EditorPrefs.DeleteKey(AUTO_FIX_PREFS_KEY);
                    autoFix = false;
                }, null);
            }
        }

        [TypeInfoBox("This asset reference is temporarily broken until the next reload, because of an error in Unity where the C# wrapper object of a prefab asset is destroyed when changes are made to that prefab asset. This error has been reported to Unity.\n\nMeanwhile, Odin can fix this for you by getting a new, valid wrapper object from the asset database and replacing the broken wrapper instance with the new one.")]
        private class FixBrokenUnityObjectWrapperPopup
        {
            private IPropertyValueEntry<T> valueEntry;

            public FixBrokenUnityObjectWrapperPopup(IPropertyValueEntry<T> valueEntry)
            {
                this.valueEntry = valueEntry;
            }

            [HorizontalGroup, Button(ButtonSizes.Large)]
            public void FixItThisTime()
            {
                for (int i = 0; i < this.valueEntry.ValueCount; i++)
                {
                    var localI = i;
                    T fixedComponent = null;
                    if (ComponentIsBroken(this.valueEntry.Values[i], ref fixedComponent) && fixedComponent)
                    {
                        this.valueEntry.Property.Tree.DelayActionUntilRepaint(() =>
                        {
                            (this.valueEntry as IValueEntryActualValueSetter<T>).SetActualValue(localI, fixedComponent);
                        });
                    }
                }

                if (GUIHelper.CurrentWindow) 
                {
                    EditorApplication.delayCall += GUIHelper.CurrentWindow.Close;
                }
            }

            [HorizontalGroup, Button(ButtonSizes.Large)]
            public void FixItAlways()
            {
                EditorPrefs.SetBool(AUTO_FIX_PREFS_KEY, true);
                autoFix = true;

                if (GUIHelper.CurrentWindow) 
                {
                    EditorApplication.delayCall += GUIHelper.CurrentWindow.Close;
                }
            }
        }
    }
}

#endif