Unity Timeline dynamically modify binding resources

Introduction:

    Timeline can be used to easily create and modify scene animations, including objects, sounds, particles, animations, special effects, custom Playables, and sub-Timelines and other resources for integration, so that scene animations with great effects can be generated more conveniently .

Sometimes when you use Timeline for cutscenes, you need to drag the specified objects to be animated into the track after creating a new Timeline in the scene, so that the track can be played when it is running, but in many cases, we need code to dynamically set the track H. For example, in the figure below, the code is required to set the Cube as the object when the game is running, and the object can use the current Track1 track information to play the corresponding action.

In Unity’s PlayableDirector class, you can get all the track information of the current Timeline resource and all the Clip information in the track, and use the corresponding API to dynamically set the track.

1. In the Start function, use Dictionary to get all current Binding track information, the key uses the track name: Animation Track, and the value is the current track, so all track information is recorded in the current dictionary.


    private PlayableDirector playableDirector;
    private readonly Dictionary<string, PlayableBinding> bindingDict = new Dictionary<string, PlayableBinding>();
    private void Start()
    {
        playableDirector = GetComponent<PlayableDirector>();

        //开始的时候,储存所有轨道信息,轨道名称作为key,Track作为value,用于动态设置
        foreach (var bind in playableDirector.playableAsset.outputs)
        {
            if (!bindingDict.ContainsKey(bind.streamName))
            {
                bindingDict.Add(bind.streamName, bind);
            }
        }
    }

2. Use the SetGenericBinding method to dynamically set the binding track

    /// <summary>
    /// 动态设置轨道
    /// </summary>
    /// <param name="trackName"></param>
    /// <param name="gameObject"></param>
    public void SetTrackDynamic(string trackName, GameObject gameObject)
    {
        if (bindingDict.TryGetValue(trackName, out PlayableBinding pb))
        {
            playableDirector.SetGenericBinding(pb.sourceObject, gameObject);
        }
    }

3. In this way, after the code uses the SetTrackDynamic method, the objects in the scene can be dynamically set to the specified track.

Guess you like

Origin blog.csdn.net/mango9126/article/details/100155999
Recommended