71 lines
1.9 KiB
C#
71 lines
1.9 KiB
C#
|
using System;
|
|||
|
using System.Collections;
|
|||
|
using System.Collections.Generic;
|
|||
|
using UnityEngine;
|
|||
|
using UnityEngine.Playables;
|
|||
|
using Object = UnityEngine.Object;
|
|||
|
|
|||
|
/// <summary>
|
|||
|
/// 对Timeline中的轨道和GameObject进行随机打乱绑定
|
|||
|
/// </summary>
|
|||
|
public class TimelineRandomScript : MonoBehaviour
|
|||
|
{
|
|||
|
//关联的Timeline的控制器
|
|||
|
public PlayableDirector director;
|
|||
|
|
|||
|
|
|||
|
private void Awake()
|
|||
|
{
|
|||
|
if (director == null)
|
|||
|
{
|
|||
|
director = GetComponent<PlayableDirector>();
|
|||
|
}
|
|||
|
if (director != null)
|
|||
|
{
|
|||
|
//把自动播放给关掉,担心在播放中时,换对象,会导致异常出现
|
|||
|
director.playOnAwake = false;
|
|||
|
}
|
|||
|
}
|
|||
|
// Start is called before the first frame update
|
|||
|
private void Start()
|
|||
|
{
|
|||
|
if (director == null)
|
|||
|
{
|
|||
|
director = GetComponent<PlayableDirector>();
|
|||
|
}
|
|||
|
|
|||
|
if (director != null)
|
|||
|
{
|
|||
|
List<Object> tracks = new List<Object>();
|
|||
|
List<Object> actors = new List<Object>();
|
|||
|
var e = director.playableAsset.outputs.GetEnumerator();
|
|||
|
while (e.MoveNext())
|
|||
|
{
|
|||
|
tracks.Add(e.Current.sourceObject);
|
|||
|
actors.Add(director.GetGenericBinding(e.Current.sourceObject));
|
|||
|
}
|
|||
|
|
|||
|
RandomList(actors);
|
|||
|
|
|||
|
for (int i = 0; i < tracks.Count; i++)
|
|||
|
{
|
|||
|
director.SetGenericBinding(tracks[i], actors[i]);
|
|||
|
}
|
|||
|
director.Play();
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
//对一个列表进行随机乱序排列
|
|||
|
private void RandomList(List<Object> actors)
|
|||
|
{
|
|||
|
int max = actors.Count;
|
|||
|
for (int i = actors.Count - 1; i >=0; i--)
|
|||
|
{
|
|||
|
int goalIdx = UnityEngine.Random.Range(0, i+1);
|
|||
|
var o = actors[i];
|
|||
|
actors[i] = actors[goalIdx];
|
|||
|
actors[goalIdx] = o;
|
|||
|
}
|
|||
|
}
|
|||
|
}
|