简述
有时我们需要获取当前TimeLine中Clip的信息(如持续时间)
方法
通过实现ISerializationCallbackReceiver接口来在序列化之前将Clip的信息存入PlayableAsset的实例中
实现
using System;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;
[System.Serializable]
public class Base : PlayableAsset, ISerializationCallbackReceiver
{
// Clip的信息(开始时间与结束时间)被储存在这里
[SerializeField][HideInInspector]
protected double inTime, outTime;
// PlayableAsset的Clip 减少搜索的次数
[NonSerialized]
private TimelineClip clip;
// Factory method that generates a playable based on this asset
public override Playable CreatePlayable(PlayableGraph graph, GameObject go)
{
return Playable.Create(graph);
}
public void OnAfterDeserialize()
{
}
// 当序列化之前会调用这个函数
// 主要的部分写在这里
public void OnBeforeSerialize()
{
// 复用Clip减少搜索
if(clip != null)
{
inTime = clip.start;
outTime = clip.end;
return;
}
// 获取所有TimeLineAsset
string[] guids = AssetDatabase.FindAssets("t:TimelineAsset");
var timelines = guids.Select(id => AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(id), typeof(TimelineAsset)));
// 找到包含这个PlayableAsset的Clip
foreach (TimelineAsset timeline in timelines)
{
if (timeline)
{
foreach (var track in timeline.GetOutputTracks())
{
foreach (var clip in track.GetClips())
{
if (clip.asset == this)
{
inTime = clip.start;
outTime = clip.end;
this.clip = clip;
}
}
}
}
}
}
}
参考
1.Unity Forum - How can I get the currently playing clip?
|