Using WaitForSeconds?

Use code tags:

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

public class Test : MonoBehaviour
{
    public GameObject prefab;
    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    void Spawn()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            Instantiate(prefab, transform.position, transform.rotation);
            StartCoroutine("waitOneSecond");
        }
    }
    IEnumerator waitOneSecond()
    {
        yield return new WaitForSeconds(1);
    }

}

I’m not sure how this worked before… this really doesn’t do anything.

Nothing calls the function ‘Spawn’.

And your code instantiates something, then starts a coroutine which just waits for a second and does nothing else.

I presume what you want is that on the press of space Spawn gets called and it waits 1 second and then instantaites something. Like this:

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

public class Test : MonoBehaviour
{
    public GameObject prefab;
    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.Space))
        {
            StartCoroutine(Spawn());
        }
    }

    IEnumerator Spawn()
    {
        yield return new WaitForSeconds(1);
        Instantiate(prefab, transform.position, transform.rotation);
    }
 
}

Note there is alternatives to this as well. Such as the simpler Invoke method that calls a method after a delay, avoiding having to do the coroutine all together:

1 Like