Hey Everyone,
I’m making an endless runner game for my current college (UK) project, but I’m unable to create a script that generates a random prefab (from a list of prefabs) one after the other. Any help with this would be appreciated so much as I am relatively new to both Unity and C#, Thanks!
Dale
I don’t recommend you to Call this CreatePrefab() function inside Update() function. As it will create infinite number of prefabs and will decrease your game performance, So I recommend you to have Entry or exit trigger to instantiate the prefab objects.
Also check this question : Infinite Runner World creation [sloved]
public GameObject[] _myPrefabs;
void Start()
{
CreatePrefab();
}
void CreatePrefab()
{
GameObject clone = Instantiate(_myPrefabs[RandomNumber()])as GameObject;
}
int RandomNumber()
{
System.Random rand = new System.Random();
return rand.Next(0,_myPrefabs.Length);
}
You may use the Random.Range function and a switch/case cicle.
EDIT: Sorry, i forgot to write that this is in Javascript. It may be useful for who is searching the answer but doesn’t write code in C#
Example:
#pragma strict
private var rand:int;
function FixedUpdate(){
rand=Random.Range(1,4);
case 1:
Instantiate(<prefab1>);
break;
case 2:
Instantiate(<prefab2>);
break;
case 3:
Instantiate(<prefab3>);
break;
case 4:
Instantiate(<prefab4);
break;
}
Maybe it is not the best way…
P.S Remember to change your physics timestep.
why case you just create
int rnd ;
rnd=Random.Range(0,5);
instantiate(tile[rnd],transform.position,transform.rotation);
…
.
.
.
…
.
.