mastertravels77 发表于 2022-2-22 11:38

Unity代码自定义Timeline

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
//绑定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的代码中可以找到
这里的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()获取了我们上面定义的真正的数据载体。
页: [1]
查看完整版本: Unity代码自定义Timeline