Hello, i whould really like a script where items will be randomly choosen to be spawned in the world, from prefabs. If you understand, comment i’d really appreciate it!
I have looked it up but i cant find to understand any of them! Thanks
(Im using JavaScript)
~carlqwe
2 Answers
2
Here is basically what you need. This is in Javascript too. Unity - Scripting API: Random.Range
If you want to randomly select a prefab too, make an array of gameobjects, as @Gilles_aerts said above, and use a random index in the “prefab” argument in the code referenced above.
Good luck!
~Matt
A possible solution would be to make some some prefabs ( lets say we make a cube, sphere and a box)
and then store these 3 prefabs in an array.
initialize an int called random and make it generate a random number from 0 to 2.
then instantiate(NameOfArray[random],NameOfArray[random].trans.pos,nameOfArray[random])
i’ll write you some code if I explained badly but I code in cSharp so my apologies.
public GameObject ListOfPrefabs; // enter the amount of different prefabs you have in the hierachry
private int random ;
Start(){
random = random.range(0,2);
instantate(ListoOfPrefabs[random], ListoOfPrefabs[random].transform.position, ListoOfPrefabs[random].quaternion.identity);
// what this code does is generate a random number ( 0,1 or 2) … and then it instantate the prefab from that list that is equal to the random number
}
I am sorry, i fixed your code up and nothing of this script works?
– carlqweYeah you might be able to add an extension method. Don't see why not. Just need to access the internal array. Should be easy to figure out.
– rageingnonsense