Last active
February 11, 2018 06:29
-
-
Save lynxelia/98190b30b06cfba1497439648db55d0e to your computer and use it in GitHub Desktop.
A replacement base class to use instead of Editor. Inheriting from this editor class will allow you to validate properties without encountering the OnValidate garbage collection bug. OnValidateProperty is also guaranteed to only execute when a change is made in the Inspector Window. It doesn't run when loading an asset into memory or loading a s…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[CanEditMultipleObjects, CustomEditor(typeof(BaseMonoBehaviour), true)] | |
public class BaseMonoBehaviourEditor : Editor | |
{ | |
public override void OnInspectorGUI() | |
{ | |
serializedObject.Update(); | |
SerializedProperty iterator = serializedObject.GetIterator(); | |
bool enterChildren = true; | |
while (iterator.NextVisible(enterChildren)) | |
{ | |
enterChildren = false; | |
OnPropertyGUI(property); | |
} | |
serializedObject.ApplyModifiedProperties(); | |
} | |
public void OnPropertyGUI(SerializedProperty property) | |
{ | |
OnPropertyGUI(property, new GUIContent(property.displayName, property.tooltip)); | |
} | |
public void OnPropertyGUI(SerializedProperty property, GUIContent label) | |
{ | |
BaseMonoBehaviour t = target as BaseMonoBehaviour; | |
EditorGUI.BeginChangeCheck(); | |
DrawProperty(property, label); | |
if (EditorGUI.EndChangeCheck()) | |
{ | |
property.serializedObject.ApplyModifiedProperties(); | |
property.serializedObject.Update(); | |
t.OnValidateProperty(property.name); | |
} | |
} | |
public void OnPropertyGUI(Rect position, SerializedProperty property, GUIContent label) | |
{ | |
BaseMonoBehaviour t = target as BaseMonoBehaviour; | |
EditorGUI.BeginChangeCheck(); | |
DrawProperty(position, property, label); | |
if (EditorGUI.EndChangeCheck()) | |
{ | |
property.serializedObject.ApplyModifiedProperties(); | |
property.serializedObject.Update(); | |
t.OnValidateProperty(property.name); | |
} | |
} | |
public virtual Rect GetPropertyControlRect(SerializedProperty property, GUIContent label, params GUILayoutOption[] options) | |
{ | |
return EditorGUILayout.GetControlRect(!string.IsNullOrEmpty(label.text), EditorGUI.GetPropertyHeight(property, label, true), options); | |
} | |
protected virtual void DrawProperty(SerializedProperty property, GUIContent label, params GUILayoutOption[] options) | |
{ | |
Rect position = GetPropertyControlRect(property, label, options); | |
DrawProperty(position, property, label); | |
} | |
protected virtual void DrawProperty(Rect position, SerializedProperty property, GUIContent label) | |
{ | |
EditorGUI.PropertyField(position, property, label); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment