WaitForSeconds();

This code is supposed to wait for 0.3 seconds then play an animation but instead it just does nothing. It is not a problem with the animation, but with the coroutine. Please help

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class splatanimhandle : MonoBehaviour {

    public Animator splat;
    public bool isOnTitle;
    public bool splatPlaying;

    // Use this for initialization
    void Start () {
        StartCoroutine ("splatScene");
        splat = GetComponent<Animator> ();
        isOnTitle = true;
    }
   
    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown (KeyCode.Space) == true) {
            if (isOnTitle == true) {
                splat.Play ("splatanim");
                isOnTitle = false;
                splatPlaying = true;
            }
        }
    }
    IEnumerator splatScene () {
        if (splatPlaying == true) {
            yield return new WaitForSeconds(0.3f);
            splat.Play("splatanim");
        }
    }
}

The coroutine looks correct to me. Is “splatPlaying” set to “true” before that coroutine runs?

It runs, checks if “splatPlaying” is true, finds that it isnt, then ends the coroutine.

You need to loop inside and check every frame.

Dude… you literally have a thread already talking about this subject 3 posts down as we speak. Is there a reason you opened a new thread?

Furthermore, you start the coroutine immediately, but don’t set splatPlaying until a key is pressed. The coroutine has already done and finished by the time you press the key.

1 Like

What you should be doing is something like this:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class splatanimhandle : MonoBehaviour {

    public Animator splat;
    public bool isOnTitle;
    public bool splatPlaying;

    // Use this for initialization
    void Start () {
        splat = GetComponent<Animator> ();
        isOnTitle = true;
    }
   
    // Update is called once per frame
    void Update () {
        if (isOnTitle && Input.GetKeyDown(KeyCode.Space)) {
            isOnTitle = false;
            this.StartCoroutine(splatScene());
        }
    }
   
    IEnumerator splatScene () {
        yield return new WaitForSeconds(0.3f);
        splat.Play("splatanim");
    }
}

Thank you. The post a while ago was different code by the way. I have a completely different problem. But it works now