Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

IE numerator waitforseconds C# in Unity not working

I’m making a game in Unity and would like to pause the script for a few seconds before playing a sound. But, for some unknown reason, it doesn’t work! I have been through countless forums to see what I’ve been doing wrong. But according to Unity’s docummentation, I’m doing it right? Can someone please help me on how to fix this? If it helps: this script is for a trigger. Code below

using System.Collections;
using UnityEngine;

public class mechstarttrigger : MonoBehaviour
{
    public GameObject rl;
    public GameObject mech;

    void Start()
    {
        Time.timeScale = 0;
        Time.timeScale = 1;
        rl.SetActive(false);
        mech.SetActive(false);
    }

    IEnumerator waitsec()
    {
        yield return new WaitForSeconds(2);
        
    }

    void OnTriggerEnter (Collider colision)
    {
        rl.SetActive(true);
        mech.SetActive(true);
        StartCoroutine(waitsec());
        FindObjectOfType<AudioManger>().Play("1");
        Destroy(gameObject);
    }

    
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Starting a Coroutine does NOT delay the code that used StartCoroutine!

What you rather want/need to do either

IEnumerator waitsec()
{
    rl.SetActive(true);
    mech.SetActive(true);

    yield return new WaitForSeconds(2);

    FindObjectOfType<AudioManger>().Play("1");
    Destroy(gameObject);
}

void OnTriggerEnter (Collider colision)
{
    StartCoroutine(waitsec());
}

Or you can go fancy and use a callback structure

IEnumerator waitsec(Action whenDone)
{
    yield return new WaitForSeconds(2);

    whenDone?.Invoke();
}

void OnTriggerEnter (Collider colision)
{
    rl.SetActive(true);
    mech.SetActive(true);

    StartCoroutine(waitsec(()=>
    {
        FindObjectOfType<AudioManger>().Play("1");
        Destroy(gameObject);
    }));
}

or actually the easiest way for you: OnTriggerEnter can be a Coroutine itself

IEnumerator OnTriggerEnter (Collider colision)
{
    rl.SetActive(true);
    mech.SetActive(true);
    yield return new WaitForSeconds(2);
    FindObjectOfType<AudioManger>().Play("1");
    Destroy(gameObject);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading