一.作为一个商业化的项目,timeline是和场景分离开,单独做成prefab加载的。因此timeline的轨道上的绑定和场景中的obj产生联系时就需要动态设置绑定。这里就介绍代码动态设置绑定的基本原理。(测试前,勾掉play on awake)
1.动态设置轨道的绑定,就是给上图中Bindings赋值
foreach (PlayableBinding bindingInfo in director.playableAsset.outputs)
bindingInfo.streamName:轨道的名字
bindingInfo.sourceObject:轨道绑定源obj
下面这一行代码就设置好了轨道的绑定
director.SetGenericBinding(bindingInfo.sourceObject, new GameObject(“bindObjName”));
2.获取轨道上的所有clips的信息
TrackAsset trackOne = bindingInfo.sourceObject as TrackAsset
var clips = trackAsset.GetClips().GetEnumerator();
每个clip 有两个属性
clip.displayName: clip的名字
clip. 此clip可查看到它自己inspector面板中的所有信息
3.不多说了,直接上代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Timeline;
using UnityEngine.Playables;
public class SetTimelineBinding : MonoBehaviour
{
PlayableDirector director;
void Start()
{
director = GameObject.FindGameObjectWithTag("direct").GetComponent<PlayableDirector>();
GetAllOuts();
}
// key:轨道名字 value:轨道对应的绑定源类型
Dictionary<string, Object> Name_BindObj = new Dictionary<string, Object>();
// key:轨道名子 value:{key:clip名字;value:clip信息}
Dictionary<string, Dictionary<string, PlayableAsset>> Track_Clips = new Dictionary<string, Dictionary<string, PlayableAsset>>();
public void GetAllOuts()
{
foreach (PlayableBinding item in director.playableAsset.outputs)
{
Debug.LogError("item.streamName=" + item.streamName);
if (!Name_BindObj.TryGetValue(item.streamName, out var obj))
{
var gameObj = GameObject.Find(item.streamName);
Name_BindObj.Add(item.streamName, item.sourceObject);
}
if (director.GetGenericBinding(item.sourceObject) == null)
{
Debug.LogError("already have binding, name="+ item.streamName);
}
else
{
Debug.LogError("轨道中绑定丢失,轨道名字是Error null binding name=" + item.streamName);
}
if (item.streamName.Equals("Markers"))
{
continue;
}
// 下面是获取每个 Track轨道中所有的clip信息
if (!Track_Clips.ContainsKey(item.streamName))
{
Track_Clips[item.streamName] = new Dictionary<string, PlayableAsset>();
}
TrackAsset trackAsset = item.sourceObject as TrackAsset;
var clips = trackAsset.GetClips().GetEnumerator();
for (; clips.MoveNext();)
{
var cur = clips.Current;
Debug.LogError("Name =" + cur.displayName);
Track_Clips[item.streamName][cur.displayName] = cur.asset as PlayableAsset;
var pa = cur.asset as PlayableAsset;
}
}
}
void SetBindings()
{
var iEnumtor = Name_BindObj.GetEnumerator();
for (; iEnumtor.MoveNext();)
{
var cur = iEnumtor.Current;
var obj = GameObject.Find("example");
SetGenericBindOne(cur.Key, obj);
}
}
void SetGenericBindOne(string trackName,Object obj)
{
director.SetGenericBinding(Name_BindObj[trackName], obj);
}
}
https://blog.youkuaiyun.com/linxinfa/article/details/79557744?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.edu_weight&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.edu_weight