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 :
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);
}