not working code(help) I want it to randomly spawn my prefabs continuously ( I have 4 of them)
using UnityEngine;
using System.Collections;
public class SpawnController : MonoBehaviour
{
public GameObject[] SquarePrefab;
public int Prefab;
void Start()
{
StartCoroutine(SquareSpawn());
int Prefab = Random.Range(0,4);
}
IEnumerator SquareSpawn()
{
while (true)
{
Instantiate(SquarePrefab[Prefab],transform.position,Quaternion.identity);
yield return new WaitForSeconds(1);
}
}
}
Answer by pekalicious · Nov 16, 2015 at 03:26 AM
You set your Prefab int at Start, which only runs once. So that int will remain the same forever. What you probably want is to change it right before you instantiate a prefab:
IEnumerator SquareSpawn()
{
while (true)
{
int Prefab = Random.Range(0,4);
Instantiate(SquarePrefab[Prefab],transform.position,Quaternion.identity);
yield return new WaitForSeconds(1);
}
}
Also, the int Prefab
in Start hides the public int Prefab
in your class. You actually don't need the public one; just delete it.
No problem. Can you accept my answer? Thank you!
Is it possible to do the same thing with Quaternion like this
int Rotation = Random.Range(0,4);
Instantiate(SquarePrefab[Prefab],transform.position,Quaternion[Rotation]);
So that the clone when spawned randomly points either left, right, up or down?
Yes. Just like how you define your prefabs in editor, you can define a bunch of Vectors and then use LookRotation to rotate the object like this: https://gist.github.com/pekalicious/d9e1367f36e4e8b3428e
How come it doesn't let you assign the W value?