Have script sleep/wait for # of secs

I know in lua there is a sleep(#) value, But in C# i need to use something that’ll make my program wait, However “yield return new WaitForSeconds(#);” Returns the error “The body of ‘EnemyAINormal.Update()’ cannot be an interator block because void is not an interator interface type”, How do I fix this? My code is below.

    using UnityEngine;
    using System.Collections;
    public class EnemyAINormal : MonoBehaviour {
    	// Update is called once per frame
    	void Update () {
    		int rndizer = Random.Range(1, 51);
    		if (rndizer == 1 ) {
    				Rigidbody clone;
    				clone = Instantiate (GameObject.Find ("Enemy"), transform.position, transform.rotation) as Rigidbody;
    				clone.AddForce (Vector3.forward / 40);
    			yield return new WaitForSeconds(1);
    		}
    		
    	}
    }

BoredMormon, pls don’t change this.

If you compare your code against the example here:

You’ll notice that your function uses void where-as the example uses IEnumerator. With that insight, hopefully the error message you get makes more sense. (Void isn’t an iterator, where-as IEnumerator is.)

I sympathize with you here because it took me much longer than usual to understand what a coroutine does.

Basically what’s going on here is that Unity doesn’t know that you want to use a timer unless you run a Coroutine. In C#, you run a Coroutine by placing a void IEnumerator in your script. Now you can put your functions you’d like to call with gaps of time inbetween them inside that IEnumerator function. The next step is to call it! If you’d like to have it called immediately, then you’ll just put StartCoroutine(MyCoRoutine()); in the Start function. However, if you’d only like to, for example, spawn an enemy when you collide with a box, then you’d put StartCoroutine(SpawnEnemy()); inside a void OnTriggerEnter function. If you’d like to spawn an enemy over and over and over, then you’re going to use what’s called an InvokeRepeating function. You can put this in place of Start Coroutine and it will do the same thing, except it calls the coroutine in intervals you define. InvokeRepeating functions are typically put in Start or Awake functions.

Here’s an example:

InvokeRepeating("SpawnEnemy",5,20);

This code will run the “SpawnEnemy” function starting 5 seconds after you call it, and then once every 20 seconds after that.

using UnityEngine;
using System.Collections;

public class SpawnEnemyScript : MonoBehaviour {
    
    void Start(){
        StartCoroutine (SpawnEnemy ());
    }

    IEnumerator SpawnEnemy(){ 
	    int rndizer = Random.Range(1, 51);
	    if (rndizer == 1 ) {
            Rigidbody clone;
	        clone = Instantiate (GameObject.Find ("Enemy"), transform.position, transform.rotation) as Rigidbody;
	        clone.AddForce (Vector3.forward / 40);
	        yield return new WaitForSeconds(1);
        }
	}
}