在做一些开场动画或者其它指定事件触发 一类功能时,需要在编辑环境下设置添加回调函数。
一开始尝试直接使用delegate 来编写,测试发现没有效果,在谷歌搜索到Unity论坛有人提到 delegate 不能被序列化到Inspector 中使用,建议使用 UnityEvent 。
UnityEvent ,其实在UGUI中经常用到,只是平时不知道是它。
比如按钮的点击事件就是
直接从 UGUI Button 的源代码中搬运出来。
先提供一个带有 UnityEvent 的类
TimeEventPlugin.cs
using UnityEngine; using System.Collections; using UnityEngine.Serialization; using System; using UnityEngine.Events; public class TimeEventPlugin : MonoBehaviour { [SerializeField] public float m_DelayTime; [SerializeField] public TimeEventTrigger m_TimeEventTrigger=new TimeEventTrigger(); private float delayTime; void Start() { delayTime = m_DelayTime; Debug.Log("TimeEventTrigger ID="+m_TimeEventTrigger.ID); } void Update() { delayTime -= Time.deltaTime; if (delayTime <= 0) { delayTime = m_DelayTime; m_TimeEventTrigger.m_TimeEvent.Invoke(); } } } [Serializable] public class TimeEventTrigger { public int ID; [Serializable] public class TimeEvent:UnityEvent{} [SerializeField] public TimeEvent m_TimeEvent=new TimeEvent(); }
using UnityEngine; using System.Collections; using UnityEditor; [CustomEditor(typeof(TimeEventPlugin))] public class TimeEventPluginEditor : Editor { SerializedProperty m_serializedTimeEventTrigger; SerializedProperty m_serializedTimeEvent; TimeEventTrigger m_TimeEventTrigger; void OnEnable() { m_serializedTimeEventTrigger = serializedObject.FindProperty("m_TimeEventTrigger"); } public override void OnInspectorGUI () { serializedObject.Update(); TimeEventPlugin plug = target as TimeEventPlugin; plug.m_DelayTime=EditorGUILayout.FloatField("m_DelayTime", plug.m_DelayTime); EditorGUILayout.PropertyField(m_serializedTimeEventTrigger,true); serializedObject.ApplyModifiedProperties(); } }
using UnityEngine; using System.Collections; public class Test : MonoBehaviour { // Use this for initialization void Start () { } public void TimeEnd() { Debug.Log("TimeEnd"); } // Update is called once per frame void Update () { } }
例子下载:
http://pan.baidu.com/s/1bnjmKdL
版权声明:本文转自http://blog.csdn.net/huutu 转载请带上 http://www.thisisgame.com.cn
在Inspector 中 设置添加回调函数 - Unity3d编辑器扩展
原文地址:http://blog.csdn.net/huutu/article/details/46918297