Unity Timeline扩展 添加停止监听、一次性清除所有监

2024-06-23  本文已影响0人  不正经的搬砖工

使用TImeline时通常需要对Timeline的播放、暂停、停止监听。

1、我们可以扩展Timeline的PlayableDirector类,添加监听接口,如下代码中的AddListener_Stopped()接口,调用PlayableDirector的stopped、played或paused添加回调行为,这儿只实现了停止的监听。

2、由于PlayableDirector的stopped是event action,可以直接通过+=/-=添加或删除某个Action,但不能像Action那样直接通过=赋值为空清除所有Action。但有时可能中途销毁Timeline,销毁时我们就需要将event所有注册的Action清除,目前我们只能使用反射来实现。实现接口为RemoveAllListeners_Stopped()。首先获取PlayableDirector对象包含的所有事件,然后遍历所有事件,找到命名为"stopped”的事件,然后获取该事件对应的成员属性信息,将成员属性信息的值置空。

实现代码如下:

using System;

using System.Reflection;

using UnityEngine.Playables;

public static class TimelineExtend

{

    /// <summary>

    /// 添加停止监听

    /// </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;

            }

        }

    }

}

上一篇 下一篇

猜你喜欢

热点阅读