使用TImeline時通常需要對Timeline的播放谎势、暫停凛膏、停止監(jiān)聽杨名。
1脏榆、我們可以擴(kuò)展Timeline的PlayableDirector類,添加監(jiān)聽接口台谍,如下代碼中的AddListener_Stopped()接口须喂,調(diào)用PlayableDirector的stopped、played或paused添加回調(diào)行為趁蕊,這兒只實現(xiàn)了停止的監(jiān)聽坞生。
2、由于PlayableDirector的stopped是event action掷伙,可以直接通過+=/-=添加或刪除某個Action是己,但不能像Action那樣直接通過=賦值為空清除所有Action。但有時可能中途銷毀Timeline任柜,銷毀時我們就需要將event所有注冊的Action清除卒废,目前我們只能使用反射來實現(xiàn)。實現(xiàn)接口為RemoveAllListeners_Stopped()宙地。首先獲取PlayableDirector對象包含的所有事件摔认,然后遍歷所有事件,找到命名為"stopped”的事件宅粥,然后獲取該事件對應(yīng)的成員屬性信息参袱,將成員屬性信息的值置空。
實現(xiàn)代碼如下:
using System;
using System.Reflection;
using UnityEngine.Playables;
public static class TimelineExtend
{
? ? /// <summary>
? ? /// 添加停止監(jiān)聽
? ? /// </summary>
? ? /// <param name="pd"></param>
? ? /// <param name="callback"></param>
? ? public static void AddListener_Stopped(this PlayableDirector pd, Action<PlayableDirector> callback)
? ? {
? ? ? ? pd.stopped += callback;
? ? }
? ? public static void RemoveAllListeners_Stopped(this PlayableDirector pd)
? ? {
? ? ? ? BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Static;
? ? ? ? EventInfo[] eventInfo = pd.GetType().GetEvents(bindingFlags);
? ? ? ? if (eventInfo == null) return;
? ? ? ? foreach(EventInfo info in eventInfo)
? ? ? ? {
? ? ? ? ? ? if(string.Compare(info.Name, "stopped")==0)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? FieldInfo fieldInfo = info.DeclaringType.GetField(info.Name, bindingFlags);
? ? ? ? ? ? ? ? if(fieldInfo != null)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? fieldInfo.SetValue(pd, null);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? }
? ? ? ? }
? ? }
}