Search Unity

Run timeline animation on click

Discussion in 'Timeline' started by SimonEfte, May 18, 2022.

  1. SimonEfte

    SimonEfte

    Joined:
    Sep 24, 2019
    Posts:
    1
    Whenever i click on my game object button i want the animation i've made to run.
    Im pretty new to Unity so help would be good!

    I know how to play an animation (not made via Timeline) on click. fakeCoin.GetComponent<Animation>().Play("Flip1");
    But it seems more complicated when your working with timeline animations
     
    ericksm703 and AntonioModer like this.
  2. Unrighteouss

    Unrighteouss

    Joined:
    Apr 24, 2018
    Posts:
    599
    Hello,

    Starting timeline playback is pretty easy to do. The Timeline GameObject has a "PlayableDirector" component; you use that to control the timeline.

    Here's an example of what you want to do:
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.Playables;
    3.  
    4. public class TimelineScript : MonoBehaviour
    5. {
    6.     [SerializeField] PlayableDirector timeline;
    7.  
    8.     void OnMouseDown()
    9.     {
    10.         timeline.Play();
    11.     }
    12. }
    Make sure you assign the timeline object to the timeline variable in the inspector. This script goes on the object you want to click on, and make sure the object also has a collider of some kind.
     
    AntonioModer likes this.
  3. Unrighteouss

    Unrighteouss

    Joined:
    Apr 24, 2018
    Posts:
    599
    Oops, I came across this again, and realized you wanted to play the timeline after clicking a button, not clicking a GameObject. You probably could have figured this out on your own, but here's an example:
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.Playables;
    3.  
    4. public class TimelineScript : MonoBehaviour
    5. {
    6.     PlayableDirector timeline;
    7.  
    8.     void Start()
    9.     {
    10.         timeline = GetComponent<PlayableDirector>();
    11.     }
    12.  
    13.     public void PlayTimeline()
    14.     {
    15.         timeline.Play();
    16.     }
    17. }
    This script would go on the timeline GameObject, and you call
    PlayTimeline()
    with a button.

    If you don't know how to call methods using buttons, you can check out 2:51 in this video:
     
    ericksm703 likes this.