- Home /
Generating pickups randomly
First of all, I must warn you I am quite a newbie on Unity, so please excuse my dumb questions. Anyway, I am developing a 2D platform game (similar do Robot Unicorn Attack), and I need to generate pickup items (like coins) randomly on the platforms. Problem is I have no idea how to do that. I already made my pickups, but they are the kind we manually place them on the screen. What I want to do is during the game, once the platform is visible, generate the pickups randomly. Thank you very much for your help.
Answer by asafsitner · Jan 11, 2012 at 05:48 PM
Make an array to hold your pickup prefabs, and place empty game objects above your platforms, where you want the pickups to be. You can make them children of the platform so it'll be easier to find them. Have a script on the platform that determine when the platform is visible, that holds the pickup locations in an array of it's own, then iterates over it and randomly chooses a pickup prefab from the pickups array.
You can hold the pickups array in an external class and reference it from every platform. Or you can have an array for each platform for greater control.
Answer by Larry-Dietz · Jan 11, 2012 at 05:56 PM
Without knowing more about the way you are coding this, the best answer I can give you is to look at the following...
The Instantiate command will let you create objects in the game world on the fly.
Hope this is of some help.
-Larry
Answer by Muzz5 · Jan 11, 2012 at 06:15 PM
var prefab : GameObject;
var spawns = GameObject.FindGameObjectsWithTag ("spawn");
for (var spawnSpot in spawns)
Instantiate (prefab, spawnSpot.transform.position, spawnSpot.transform.rotation);
There you go. Spawns an object at all places tagged spawn
UnityException: You are not allowed to call this function when declaring a variable.
What To Do ????
hey , i tried using this piece of code.It doesn't just spawn one object , but multiple copies of it (like in an infinite loop)..what to do ?
Your answer
![](https://koobas.hobune.stream/wayback/20220613062900im_/https://answers.unity.com/themes/thub/images/avi.jpg)