A relative simple way to get the instance object from a custom property drawer that draws a serialized class inside a component
using UnityEngine; | |
using System.Collections; | |
public class Example : MonoBehaviour | |
{ | |
public ExampleClass example; | |
void Start() | |
{ | |
} | |
void Update() | |
{ | |
} | |
} |
using UnityEngine; | |
using System; | |
[Serializable] | |
public class ExampleClass | |
{ | |
public string field = "example string"; | |
public void Print() | |
{ | |
Debug.Log("ExampleClass.field: " + field); | |
} | |
} |
using UnityEngine; | |
using UnityEditor; | |
[CustomPropertyDrawer (typeof(ExampleClass))] | |
public class ExampleProperty : NestablePropertyDrawer | |
{ | |
protected new ExampleClass propertyObject { get { return (ExampleClass)base.propertyObject; } } | |
private SerializedProperty stringField = null; | |
protected override void Initialize(SerializedProperty prop) | |
{ | |
base.Initialize(prop); | |
if (stringField == null) | |
stringField = prop.FindPropertyRelative("field"); | |
} | |
public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label) | |
{ | |
base.OnGUI(position, prop, label); | |
EditorGUI.BeginProperty(position, label, prop); | |
EditorGUI.BeginChangeCheck(); | |
EditorGUI.PropertyField(position, stringField); | |
if (EditorGUI.EndChangeCheck()) | |
{ | |
stringField.serializedObject.ApplyModifiedProperties(); | |
propertyObject.Print(); | |
} | |
EditorGUI.EndProperty(); | |
} | |
} |
using UnityEngine; | |
using UnityEditor; | |
using Object = System.Object; | |
public class NestablePropertyDrawer : PropertyDrawer | |
{ | |
protected Object propertyObject = null; | |
protected virtual void Initialize(SerializedProperty prop) | |
{ | |
if (propertyObject == null) | |
{ | |
string[] path = prop.propertyPath.Split('.'); | |
propertyObject = prop.serializedObject.targetObject; | |
foreach (string pathNode in path) | |
{ | |
propertyObject = propertyObject.GetType().GetField(pathNode).GetValue(propertyObject); | |
} | |
} | |
} | |
public override void OnGUI(Rect position, SerializedProperty prop, GUIContent label) | |
{ | |
Initialize(prop); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment