Unity Interface Serialization-Expose Interface field In Inspector

时间:2014-10-10 21:11:14   收藏:0   阅读:495

Unity has some quirks about their inspector, so as a preface they are listed here:

When we want to Serialize the Interface,What we can do?

Unity, by itself, does not expose fields that are of an interface type. It is possible to manually enable this functionality by implementing a custom inspector each time as Mike 3 has pointed out,but even then the reference would not be serialized ("remembered" between sessions and entering/exiting playmode).

It is possible however to create a serializable container object that wraps around a Component field (which is serialized) and casts to the desired interface type through a generic property. And with the introduction of custom property drawers into Unity, you can effectively expose a serialized interface field in your scripts without having to write a custom inspector / property drawer each time.

Some simple demo code :

using UnityEngine;

[System.Serializable]
public class InterfaceHelper  {

	public Component target;

	public T getInterface<T>() where T : class
	{
		return target as T;
	}
}

And the Custom property drawer:

using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(InterfaceHelper))]
public class EditorInterfaceHelper : PropertyDrawer {

	public override void OnGUI(Rect pos, SerializedProperty prop, GUIContent label)
	{
		EditorGUI.BeginProperty(pos, label, prop);
		pos = EditorGUI.PrefixLabel(pos,GUIUtility.GetControlID(FocusType.Passive),label);
		EditorGUI.PropertyField(pos,prop.FindPropertyRelative("target"),GUIContent.none);
		EditorGUI.EndProperty();
	}
}

Usage:

public interface IData
{
	void getData();
}
#define
public InterfaceHelper dataSrc;
...
//call the function
dataSrc.getInterface<IData>().getData();


The interface field in inspector is like this:

bubuko.com,布布扣

Of course, You can use abstract class instead sometimes,but if you do that, you will miss the benefit of mul-inherit.

参考:

http://codereview.stackexchange.com/questions/65028/inspector-interface-serializer

http://answers.unity3d.com/questions/46210/how-to-expose-a-field-of-type-interface-in-the-ins.html

http://answers.unity3d.com/questions/783456/solution-how-to-serialize-interfaces-generics-auto.html

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!