Makes object appear and disappear after a few seconds

It did not work somehow…

public class Coroutine : MonoBehaviour
{
[SerializeField] private GameObject laser;

// Start is called before the first frame update
void Start()
{
    StartCoroutine(ShowAndHide(laser, 3.0f));   
}

IEnumerator ShowAndHide(GameObject go, float delay)
{
    laser.SetActive(true);
    yield return new WaitForSeconds(delay);
    laser.SetActive(false);
}

}

I myself don’t like coroutines much, I would use Invoke.

void Start()
{
    Invoke("Show",1f);
}
Show()
{
    laser.SetActive(true);
    Invoke("Hide",3f);
}
Hide()
{
    laser.SetActive(false); 
}

The code-example should work fine.
I shouldn’t have to mention this, but please make sure, that you actually have a GameObject with the enabled Coroutine script in your scene, where the laserfield is assigned.


If that’s not it, there’s two issues I can think of, that would make this not work as expected:

  1. The GameObject containing your Coroutine script is inactive. Coroutine can only run on active MonoBehaviours, meaning gameObject.activeInHierarchy should return true.
  2. You are manipulating Time.timeScale, so your waiting time is distorted in some way or another. In that case you may want to try WaitForSecondsRealtime.

I would also advise against naming your class Coroutine, as that name is taken by a class in the UnityEngine namespace.
If this doesn’t solve your problem, it would be helpful to know, what works and what doesn’t.
See if there is anything useful in the console or try using Debug.Log to see which part of your code executes and which doesn’t to narrow down the problem.

this works for me just fine:

 public GameObject laser;
    void Start()
    {
        StartCoroutine(ShowAndHide(3.0f));
    }
    IEnumerator ShowAndHide(float delay)
    {
        laser.SetActive(true);
        yield return new WaitForSeconds(delay);
        laser.SetActive(false);
    }