How to Restart a Playable Director in Unity
Objective: How to restart a Timeline at the press of a key by using a simple C# Script.
Tables of Contents
Access Via Inspector
Restarting your Timeline is a lot simpler than it sounds, let’s start by creating a SeralizeField global variable, we will use this to create a slot in the Inspector that allows us to access the Playable Director with ease.
Drag the Playable Director into the newly created slot (this will be on the object to which the script is attached).
Now we create a void function to handle the restart logic.
Code Insights
- Check if the Playable Director is null. This is a best practice approach since objects can be inactive or missing for a variety of different reasons, and trying to operate with a missing field will cause an error.
- _playableDirector.Stop: Stop playing the director, which is essential before restarting.
- _playableDirector.time = 0: This reverts the Timeline to the starting point.
- _playableDirector.Evaluate: Ensures that the Timeline is evaluated at a given point in time(in this case our time = 0) and updates it accordingly. Essentially, this will make sure the playhead moves back to the start.
- _playableDirector.Play: Now that it’s back in 0(the start) we use Play start playing again.
The Result
Hope this was helpful! Check out my portfolio! Currently looking for opportunities in the game industry!