Im trying to make something spawn every 5 seconds but whenever I do, it just spawns hundreds without waiting, can someone help me out here, there is also a error saying it can’t be in fixed update because " ‘void’ is not an iterator interface type"
my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoinDropper : MonoBehaviour
{
public GameObject prefab;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
Vector2 position = new Vector2(Random.Range(-10f, 10f), Random.Range(3f, 3f));
Instantiate(prefab, position, Quaternion.identity);
yield return new WaitForSeconds(5);
}
@TCemAlpaydin is correct, the yield return commands must be inside of a Coroutine. Also, the yield return new WaitForSeconds(5); needs to be before the code you want to call after waiting for 5 seconds. This is what that might look like:
void Start()
{
StartCoroutine(SetRandomPosition(5));
}
private IEnumerator SpawnAfterDelay(float waitTime)
{
yield return new WaitForSeconds(waitTime);
Vector2 position = new Vector2(Random.Range(-10f, 10f), Random.Range(3f, 3f));
Instantiate(prefab, position, Quaternion.identity);
}
This code will wait 5 seconds upon Start, and then instantiate the prefab at the random position.