Search Unity

Alter keys on a simple one track timeline via code

Discussion in 'Timeline' started by Ziplock9000, Aug 13, 2017.

  1. Ziplock9000

    Ziplock9000

    Joined:
    Jan 26, 2016
    Posts:
    360
    I have a car that uses a single track timeline to animate a car object's position on a single axis. This track is very simple and contains 4 keys inside of an "Animation Track" that alter the car's x axis. As there are multiple cars in the scene, I'd like to give each one slightly different parameters which means I want to be able to alter the values and time of these keys in the object's Start(); before I Evaluate the PlayableDirector to start it.

    How can I access the keys from code from the PlayableDirector?

    This is as far as I got:

    Code (csharp):
    1.  
    2.         director = this.GetComponent<PlayableDirector>();
    3.         TimelineAsset timelineAsset = (TimelineAsset) director.playableAsset;
    4.         TrackAsset track = timelineAsset.GetOutputTrack(0);
    5.         AnimationTrack animTrack = (AnimationTrack) track;
    6.         GameObject binding = (GameObject) director.GetGenericBinding(animTrack); //The GameObject this track is binded to (The car)
    7.         var animator = binding.GetComponent<Animator>();
    8.  
    9.         //Something needs to happen here to get the AnimationCurve from the animator I think?
    10.  
    11.         AnimationCurve ac = new AnimationCurve();
    12.         ac.keys[1].time = 10;
    13.  
     
    Last edited: Aug 13, 2017
  2. seant_unity

    seant_unity

    Unity Technologies

    Joined:
    Aug 25, 2015
    Posts:
    1,516
    If you convert the track into clip mode, you can get the containing animation clip through the timeline clip.

    (track.GetClips().First().asset as AnimationPlayableAsset).clip.

    Alternatively if you don't want to use clip mode, you can use SerializedProperties (or reflection) to get the "m_AnimClip" field on the animation track. But there is no public accessor for that.
     
  3. Ziplock9000

    Ziplock9000

    Joined:
    Jan 26, 2016
    Posts:
    360
    Thanks, I'll give this a try.