介绍
Unity Timeline 的 ControlTrack 控制的 Prefab 有两种方法
-
Source Game Object
-
Prefab
代码
以下函数可以获取 Source Game Ojbect 和 Prefab实例后的 GameObject Instance
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;
public static class TimelineUtil
{
public static List<GameObject> getControlTrackGameObjectInstanceList(PlayableDirector playableDirector)
{
List<GameObject> rs = new List<GameObject>();
//--- 用 sourceGameObject 的
var timeline = playableDirector != null ? (playableDirector.playableAsset as TimelineAsset) : null;
if (timeline != null)
{
foreach (var t in timeline.GetOutputTracks())
{
var controlTrack = t as ControlTrack;
if (controlTrack != null)
{
foreach (var c in t.GetClips())
{
var controlPlayableAsset = c.asset as ControlPlayableAsset;
if (controlPlayableAsset != null)
{
if (controlPlayableAsset.prefabGameObject == null)
{
GameObject sourceObject = controlPlayableAsset.sourceGameObject.Resolve(playableDirector);
if (sourceObject != null)
{
rs.Add(sourceObject);
}
}
}
}
}
}
}
//--- 用 Prefab 的
PlayableGraph playableGraph = playableDirector.playableGraph;
if (playableGraph.Equals(default(PlayableGraph)) == false && playableGraph.IsValid() == true)
{
//PlayableGraph 已经初始化
int rootPlayableCount = playableGraph.GetRootPlayableCount();
for (int _rootPlayableIdx = 0; _rootPlayableIdx < rootPlayableCount; _rootPlayableIdx++)
{
Playable playable = playableGraph.GetRootPlayable(_rootPlayableIdx);
getPrefabControlPlayableGameObjectInstanceList(playable, rs);
}
}
//---
return rs;
}
public static void getPrefabControlPlayableGameObjectInstanceList(Playable playable, List<GameObject> rs)
{
int inputCount = playable.GetInputCount();
if (playable.GetPlayableType() == typeof(PrefabControlPlayable))
{
ScriptPlayable<PrefabControlPlayable> sp = (ScriptPlayable<PrefabControlPlayable>)playable;
GameObject _instance = sp.GetBehaviour().prefabInstance;
if (_instance)
{
rs.Add(_instance);
}
}
//--childrend
for (int i = 0; i < inputCount; i++)
{
Playable _childPlayable = playable.GetInput(i);
getPrefabControlPlayableGameObjectInstanceList(_childPlayable, rs);
}
}
}
用法
PlayableDirector playableDirector = this.GetComponent<PlayableDirector>();
List<GameObject> rs = TimelineUtil.getControlTrackGameObjectInstanceList(playableDirector);
for (int i = 0; i < rs.Count; i++)
{
Debug.Log($"(i):{i}," + $"(rs[i]):{rs[i]},");
}
Console输出: