Spawn prefab at a random time C#
Hi Everyone,
I have written code to spawn random objects out of my resources folder. after every second using invoke repeating.
This all works but I am now trying to spawn these objects at a random time between 1 and 3 seconds. The code I have written spawn one object and then does not spawn any more.
Please can someone help me figure out how to use a random time that works - maybe Invoke Repeating is not the best option?
Here is the code I have tried so far
using UnityEngine;
using System.Collections;
public class spawncar : MonoBehaviour {
public int totalNumberOfItemsInAvailableCars = 3;
public int mint;
public int maxt;
public int calculatedtime;
void Start () {
InvokeRepeating("spawncars", 2,calculatedtime);
Debug.Log ("Launched");
}
void spawncars(){
int randomNum = Random.Range (0, totalNumberOfItemsInAvailableCars);
Object objTemp = Resources.Load ("cars/" + randomNum);
Instantiate (objTemp);
}
void Update(){
calculatedtime = Random.Range (mint, maxt);
}
}
Answer by SoulGameStudio · Jan 19, 2016 at 10:35 AM
Hi, you call InvokeRepeating in the Start only once using calculatedtime. So no matter if you change this value later in the Update, it will keep InvokeRepeating with the value you gave in the Start.
A simple solution would be to do something like (not tested):
void Start () {
// Start a simple timer
Invoke("spawncars", 2);
Debug.Log ("Launched");
}
void spawncars(){
CancelInvoke() // Stop the timer (I don't think you need it, try without)
int randomNum = Random.Range (0, totalNumberOfItemsInAvailableCars);
Object objTemp = Resources.Load ("cars/" + randomNum);
Instantiate (objTemp);
// Start a new timer for the next random spawn
Invoke("spawncars", Random.Range (mint, maxt));
}
Perfect answer! works exactly as I needed it to. thank you