Timeline—Playable Track

作者:追风剑情 发布于:2020-6-17 15:38 分类:Unity3d

Playable Track支持在时间轴上放置脚本,并由Timeline控制脚本中生命周期函数的触发。

一、工程结构

55555.png

在场景中创建GameObject并挂上Playable Director组件

6666.png

创建MyPlayableAsset.cs和MyPlayableBehaviour.cs脚本

4444.png

MyPlayableAsset.cs


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.UI;

[System.Serializable]
public class MyPlayableAsset : PlayableAsset
{
    //引用场景对象
    [SerializeField]
    private ExposedReference<Text> m_Text;
    [SerializeField]
    private string msg;

    // 创建一个PlayableBehaviour
    public override Playable CreatePlayable(PlayableGraph graph, GameObject go)
    {
        var playable = ScriptPlayable<MyPlayableBehaviour>.Create(graph);
        var myPlayableBehaviour = playable.GetBehaviour();
        myPlayableBehaviour.Initialize(m_Text.Resolve(playable.GetGraph().GetResolver()), msg);
        return playable;
    }
}


MyPlayableBehaviour.cs


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.UI;

// PlayableBehaviour在PlayableAsset.CreatePlayable()方法中创建对象
public class MyPlayableBehaviour : PlayableBehaviour
{
    private Text m_Text;
    private string msg;

    public void Initialize(Text text, string msg)
    {
        Debug.Log("MyPlayableBehaviour.Initialize()");
        this.m_Text = text;
        this.msg = msg;
    }

    // Timeline开始播放时调用
    public override void OnGraphStart(Playable playable)
    {
        Debug.Log("OnGraphStart:Timeline 开始运行时调用");
    }

    // Timeline停止播放时调用
    public override void OnGraphStop(Playable playable)
    {
        Debug.Log("OnGraphStop:Timeline 停止时调用");
    }

    // 播放头进入PlayableAsset时调用
    public override void OnBehaviourPlay(Playable playable, FrameData info)
    {
        Debug.Log("OnBehaviourPlay:Timeline 播放头进入PlayableAsset时调用");
        if (this.m_Text != null)
            this.m_Text.text = msg;
    }

    // 当播放头离开PlayableAsset时调用
    public override void OnBehaviourPause(Playable playable, FrameData info)
    {
        Debug.Log("OnBehaviourPause:Timeline 当播放头离开PlayableAsset时调用");
    }

    // 当播放到PlayableAsset上面时每帧调用
    public override void PrepareFrame(Playable playable, FrameData info)
    {
        //Debug.Log("PrepareFrame:Timeline PlayableAsset每帧调用");
    }
}


创建时间线并将MyPlayableAsset拖到相应帧上

11111.png

222222.png

为MyPlayableAsset1和MyPlayableAsset2设置参数

3333.png

二、运行测试

当Timeline播放到MyPlayableAsset1上时,屏幕上会显示“第一条消息”,当播放到MyPlayableAsset2时屏幕上会显示“第二条消息”

1111.png

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号