How to detect end of a timeline (C#)
Hello all :)
I'm getting starting with Timeline, the new feature of Unity, and it's working like a charm!
I'm trying to detect the end of a timeline. So far, I found this :
_director = transform.GetComponentInChildren<PlayableDirector>();
And this in a coroutine :
if (_director.playableGraph.IsDone())
{
OnEnd();
}
Actually, it's not working... (Object reference not set to an instance)
I'm looking for a more reliable way to do this. Do you know if there's any events? Maybe this? But I don't know how to get the PlayableBehaviour instance from the PlayableDirector.
Thanks a lot for your help!
[EDIT]
I found this way but I'm still not fully satisfied :
public IEnumerator CheckEnd()
{
while (Math.Abs(_director.duration - _director.time) > 0.2)
{ yield return new WaitForEndOfFrame(); }
OnEnd();
}
public void OnEnd()
{
Debug.Log("On end");
}
What are you wanting it to do now? I'm sorry, but I don't know what you're question is. Does it work? yes. Is it reliable... yes? I mean, how is it not working. Then we can help.
Answer by CapnCromulent · Jul 12, 2018 at 10:12 PM
As of 2018.1, you can listen for an event on the PlayableDirector: https://docs.unity3d.com/ScriptReference/Playables.PlayableDirector-stopped.html
Seems like the event is broken in Unity 2019.1.4f. I am going to use the polling solution.
you're right, it does seem to be broken - I've personally used signals for a bit more flexibility and less polling, for anyone who comes across this
Answer by deneme09 · Sep 07, 2017 at 11:13 AM
I've been trying to solve this problem for a few hours and I solved it! You can try this code.
if (GetComponent<PlayableDirector>().state != PlayState.Playing)
{
//your code
}
I hope it works.
Respect from Turkey :)
I thought it is not good idea to put such code to check it every frames,why not try to add a animation event at the last of the timeline
I used this approach in the past but I had a bad side effect: if the application lost focus, the play state change.
So is not working in that case.
Answer by pantoygames · Aug 20, 2021 at 01:55 AM
Start this coroutine
private IEnumerator PlayTimelineRoutine(PlayableDirector playableDirector, Action onComplete)
{
playableDirector.Play();
yield return new WaitForSeconds((float) playableDirector.duration);
onComplete();
}