- Home /
Place object randomly at any predefined spawn point
I have a variable which houses all the "Create Empty" game objects which are being used as spawn points. How do I randomly choose a spawn point and then get its position which I'll then use as the position for the newly instanced object.
function Start () {
var spawnTrgts = GameObject.FindGameObjectsWithTag("Respawn");
}
var newObject : Transform;
InvokeRepeating("LaunchProjectile", 0.5, 0.3);
function LaunchProjectile () {
var spawnPos = Random.Range(-2.5, 2.5);
transform.position = Vector3(spawnPos,1,0);
Instantiate(newObject, transform.position, transform.rotation);
}
Answer by JokerMartini · Jul 19, 2012 at 12:56 AM
Got it working!!! Do I have to keep the +pragmaStrict at the top of all my javascripts?
#pragma strict
var spawnTrgts : GameObject[];
var newTarget : Transform;
function Start () { //initialize spawning points array
spawnTrgts = GameObject.FindGameObjectsWithTag("Respawn");
// Debug.Log(spawnTrgts.Length);
}
// Starting in 0.5 seconds, a projectile will be launched every 0.3 seconds
InvokeRepeating("LaunchProjectile", 0.5, 0.3);
function LaunchProjectile () {
var spawnPos = spawnTrgts[(Random.Range(0, spawnTrgts.Length))].transform.position; //randomly return position of a spawn point
Instantiate(newTarget, spawnPos, Quaternion.identity);
// Debug.Log(spawnPos);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613074354im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to follow multiple clones positions of an instantiate prefab having a velocity ? 1 Answer
How can I get a GameObject's transform in game and set that to a variable? 1 Answer
Use GameObject's global position instead of local position 3 Answers
How do I get the opposite position of an object that spins around another object... 0 Answers
Why does this script spawn 13 ClickEffect prefabs instead of 1? 2 Answers