Search code examples
c#unity-game-enginecoroutine

How to execute a coroutine when user clicks on a gameobject?


I am trying to delay the spawning of my prefab, and I tried to do this with coroutines. In play mode, the spawning occurred first, before the Debug message was displayed to show that 2 seconds had elapsed. So I concluded that my Spawn() function is working and my coroutine was executed, just in the wrong order. Below is the code, attached to a game object which will spawn my prefab in its place on click.

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

public class EmptyScript : MonoBehaviour
{
    public int id;
    public GameObject camera;
    Coroutine coroutine;

    public IEnumerator DelaySpawn()
    {
        yield return new WaitForSeconds(2);
        Debug.Log("2 seconds");

    }

    private void OnMouseDown()
    {
        coroutine = StartCoroutine(DelaySpawn());
        camera.GetComponent<GameScript>().Spawn(this.gameObject, id);
    }
}

I expected the spawn to be delayed, but it was not. Thank you for helping me out.


Solution

  • You should move the spawn code after the yield retrun like the debug you've set up, then the log should be executed at the same time:

    public IEnumerator DelaySpawn()
    {
        yield return new WaitForSeconds(2);
        Debug.Log("2 seconds");
        camera.GetComponent<GameScript>().Spawn(this.gameObject, id);
    }
    
    private void OnMouseDown()
    {
        coroutine = StartCoroutine(DelaySpawn());
    }