找回密码
 立即注册
查看: 324|回复: 0

[笔记] Unity代码自定义Timeline

[复制链接]
发表于 2022-2-22 11:38 | 显示全部楼层 |阅读模式
Timeline分为三个部分:(1)Track、(2)Clip、(3)Mixer


概括

1、先自定义一个脚本Track来表示1,然后自定义一个脚本Clip来表示2
2、为了指定哪个Track可以创建哪类Clip),在Track中加个Clip的标签。
3、Clip包含两部分,一部分提供在Inspector编辑就是Clip脚本,一部分真正承载数据写一个Behaviour脚本。
4、写一个脚本Mixer指定混合的表现也就是3
下面用代码自定义这三部分。
1、Track



右键可以出现自定义的Track
[TrackClipType(typeof(CustomClip))]//绑定Clip
public class CustomTrack : TrackAsset
{
    public override Playable CreateTrackMixer(PlayableGraph graph, GameObject go, int inputCount)
    {
        return ScriptPlayable<CustomMixer>.Create(graph, inputCount);//绑定Mixer
    }
}
这里面有两部分,一个是绑定的Clip,适用的Mixer,后面介绍。
2、Clip

右键可以出现自定义的Clip


using UnityEngine;
using UnityEngine.Playables;

public class CustomClip : PlayableAsset
{
    public CustomBehaviour template = new CustomBehaviour();//这里是自定义的数据载体
    public int x;//这里只是为了在Inspector中编辑数值
    public override Playable CreatePlayable(PlayableGraph graph, GameObject owner)
    {
        var temp = ScriptPlayable<CustomBehaviour>.Create(graph, template);
        var tb = temp.GetBehaviour();
        tb.x = x;//这里是把编辑的clip数值传给载体,方便在Mixer中使用
        return temp;
    }
}
为了把Clip和Track绑定起来需要在Track中加标签,在Track的代码中可以找到
[TrackClipType(typeof(CustomClip))]这里的Clip并不是数据的载体,在脚本中定义的x,也只是可以在Inspector中编辑。


真正的数据载体是创建一个Behaviour,上面创建了template 作为数据载体。
Behaviour的定义
public class CustomBehaviour : PlayableBehaviour
{
    public float x;
}
3、Mixer

Mixer就是两个Clip混合的部分,可以自定义渐变的过程
public class CustomMixer : PlayableBehaviour
{
    private TimelineTest t;
    public override void OnGraphStart(Playable playable)
    {
        base.OnGraphStart(playable);
        t = GameObject.Find("GameObject/Cube").GetComponent<TimelineTest>();
        Debug.Log("找到了TimelineTest");
    }

    public override void ProcessFrame(Playable playable, FrameData info, object playerData)
    {
        int inputCount = playable.GetInputCount();
        float mix = 0;
        //获取有几个输入的混合
        for (int i = 0; i < inputCount; i++)
        {
            float inputWeight = playable.GetInputWeight(i);
            ScriptPlayable<CustomBehaviour> inputPlayable = (ScriptPlayable<CustomBehaviour>)playable.GetInput(i);
            var input = inputPlayable.GetBehaviour();
            mix += input.x * inputWeight;//计算权重与Clip真实值的乘积
        }
        t.TimelinProperty = mix;
    }
}
这里就是通过inputPlayable.GetBehaviour()获取了我们上面定义的真正的数据载体。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Unity开发者联盟 ( 粤ICP备20003399号 )

GMT+8, 2024-4-28 22:52 , Processed in 0.093620 second(s), 27 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表