- Home /
Creating a random prefab generator in C# for endless runner
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
Answer by iamvishnusankar · Feb 12, 2014 at 12:49 PM
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]][1]
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);
}
[1]: http://answers.unity3d.com/questions/637266/infinite-runner-world-creation.html
Thanks for responding so quickly :) after looking at both of the answers you provided, I decided to use the box collider method. I was just wondering what I would have to write so that once a prefab contacts the box collider it will be destroyed and instantiate a new random prefab? Once again thank you so much for taking time to help me.
don't forget to leave an acceptance for this answer if you found its helpful. Cheers :-)
Answer by Crax · Feb 12, 2014 at 04:10 PM
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.
Answer by Hamilcar-games · Jun 10, 2017 at 09:51 AM
why case you just create
int rnd ;
rnd=Random.Range(0,5);
instantiate(tile[rnd],transform.position,transform.rotation); ... . .
. .. . .