Created
January 23, 2017 08:56
-
-
Save Chman/a1e980a471d14077cc3ce8950c039971 to your computer and use it in GitHub Desktop.
Property attribute / drawer
This file contains 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
using UnityEngine; | |
/// <summary> | |
/// Allows the use of C# property as inspector values in Unity. | |
/// </summary> | |
/// <example> | |
/// <code> | |
/// [SerializeField, GetSet("SomeFloat")] | |
/// private float _someFloat; | |
/// public float SomeFloat | |
/// { | |
/// get { return _someFloat; } | |
/// private set { _someFloat = value; } | |
/// } | |
/// </code> | |
/// </example> | |
public sealed class GetSetAttribute : PropertyAttribute | |
{ | |
public readonly string Name; | |
public bool IsDirty; | |
public GetSetAttribute(string name) | |
{ | |
Name = name; | |
} | |
} |
This file contains 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
using UnityEngine; | |
using UnityEditor; | |
using System; | |
using System.Reflection; | |
[CustomPropertyDrawer(typeof(GetSetAttribute))] | |
internal sealed class GetSetDrawer : PropertyDrawer | |
{ | |
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) | |
{ | |
var attribute = (GetSetAttribute)base.attribute; | |
EditorGUI.BeginChangeCheck(); | |
EditorGUI.PropertyField(position, property, label); | |
if (EditorGUI.EndChangeCheck()) | |
{ | |
attribute.IsDirty = true; | |
} | |
else if (attribute.IsDirty) | |
{ | |
object parent = GetParentObject(property.propertyPath, property.serializedObject.targetObject); | |
var type = parent.GetType(); | |
var info = type.GetProperty(attribute.Name); | |
if (info == null) | |
Debug.LogError("Invalid property name \"" + attribute.Name + "\""); | |
else | |
info.SetValue(parent, fieldInfo.GetValue(parent), null); | |
attribute.IsDirty = false; | |
} | |
} | |
object GetParentObject(string path, object obj) | |
{ | |
var fields = path.Split('.'); | |
if (fields.Length == 1) | |
return obj; | |
var info = obj.GetType().GetField(fields[0], | |
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); | |
obj = info.GetValue(obj); | |
return GetParentObject(string.Join(".", fields, 1, fields.Length - 1), obj); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment