- Home /
spawning random objects at 2 defined points
hey all, so ive got two empty's set up , one on the top and one on the bottom of the screen. I have 4 different shaped objects that are prefabs, what i wish to do is take it in turns every second or so and spawn 1 of the 4 objects either at the top empty of the bottom one, taking it in turns with each spawn location. i have no idea where to begin lol. i have got an outline of what needs to happen
-1 second PASSED
-random pick object out of 4 prefabs
-spawn object at top -CHANGE ACTIVE SPAWN TO BOTTOM-
-1 second PASSED
-random pick object out of 4 prefabs
-spawn object at bottom -CHANGE ACTIVE SPAWN TO TOP-
-REPEAT
thankyou
Answer by NickP_2 · Feb 05, 2014 at 08:20 PM
If you put this in a c# script, define the top and bottom position in the scripts inspector, and the prefabs in the array in the inspector, this will keep spawning a random object randomly, switching from a top position to bottom position
public Transform[] objects;
public Vector3 topPosition, downPosition;
private bool spawning = false, isTop = true;
void Update()
{
//if not spawning, start a new spawn
if(!spawning)
StartCoroutine(Spawn());
}
IEnumerator Spawn()
{
spawning = true;
//select random object out of array
Transform randomObj = objects[Random.Range(0, objects.Length)];
Transform clone;
switch(isTop)
{
case true:
clone = Instantiate(randomObj, topPosition, Quaternion.identity) as Transform;
isTop = false;
break;
case false:
clone = Instantiate(randomObj, downPosition, Quaternion.identity) as Transform;
isTop = true;
break;
}
yield return new WaitForSeconds(1);
spawning = false;
}
Thankyou! that works great however how could i make it so the spawn points are set to an empty's position? the camera is always moving to the right so having set x,y and z positions doesnt work. sorry to be a bother. also would it be difficult to make 2 sets of arrays? if top spawn is used it picks and object from one of the arrays, wheer bottom spawn picks a random object from the other set.
again thankyou
never$$anonymous$$d about the two arrays, i managed to make a model that can be used both ways :)
Can you define "empty's position"? Do you mean a Vector3.zero? which is 0 for x, y, z?
Your answer
Follow this Question
Related Questions
Spawn random prefabs at multiple locations 1 Answer
Problem with random spawning and coroutine 1 Answer
How can I align instantiated prefabs randomly on runtime #C 0 Answers
How to make an object/prefab choose between multiple given positions to spawn into? 1 Answer
How do I spawn a random prefab? 1 Answer