I’ve been trying to spawn two objects at random. But the random function generates only one random value at runtime, and so only one of the object gets spawned. I want both of them to spawn at random intervals. Help!
Thank You!
public float SpawnTime;
public GameObject Object1;
public GameObject Object2;
private int i;
// Use this for initialization
void Start () {
i = Random.Range (1, 6);
StartSpawn ();
}
void Update () {
}
public void StartSpawn() {
if (i > 3) {
InvokeRepeating ("SpawnObject1", 0.2f, SpawnTime);
}
else
InvokeRepeating ("SpawnObject2", 0.2f, SpawnTime);
}
void SpawnObject1(){
Instantiate(Object1, new Vector3(transform.position.x,0,0), Quaternion.identity);
}
void SpawnObject2(){
Instantiate(Object2, new Vector3(transform.position.x,0,0), Quaternion.identity);
}
}
Start() is executed once, that’s why you get only one random value.
public float SpawnTime;
public GameObject Object1;
public GameObject Object2;
// Use this for initialization
void Start () {
StartCoroutine(SpawnObject ());
}
public IEnumerator SpawnObject() {
int i = Random.Range (1, 6);
if (i > 3){
Instantiate(Object1, new Vector3(transform.position.x,0,0), Quaternion.identity);
}else{
Instantiate(Object2, new Vector3(transform.position.x,0,0), Quaternion.identity);
}
yield return new WaitForSeconds(SpawnTime);
StartCoroutine(SpawnObject ());
}
If the only thing you want to randomise is the object you instantiate, there’s really no reason to have multiple different method calls. And if you want to spawn a different object every time, you should call Random.Range() every time you Instantiate, not just once when the app/level starts.
void SpawnRandomObject(){
int i = Random.Range(1, 6);
GameObject obj;
if (i > 3){
obj = Object1;
} else {
obj = Object2;
}
Instantiate(obj, new Vector3(transform.position.x,0,0), Quaternion.identity);
}
Then just “InvokeRepeating” this one method.
Note that Random.Range with integers never returns the second parameter, so with (1, 6) it returns numbers 1, 2, 3, 4 and 5, making object 1 spawn less often than 2