- Home /
Spawning objects at random Vector3
I've got some ammo pickups around my game map, working perfectly. Now all I need to do is get them spawning at random points at runtime. I thought to save problems with height, I'd spawn them up in the air, and let them fall and land on the terrain surface. The ammo boxes spawn fine, but all at 0, 0, 0. And I can't work out why.
using UnityEngine;
using System.Collections;
public class ammoSpawn : MonoBehaviour {
public Transform ammoDrop;
public int numToSpawn;
public Vector3 position;
void Awake()
{
Vector3 position = new Vector3(Random.Range(100.0F, 1000.0F), 70, Random.Range(100.0F, 1000.0F));
}
void Start()
{
int spawned = 0;
while (spawned < numToSpawn)
{
spawned++;
Instantiate(ammoDrop, position, Quaternion.identity);
}
}
}
I know in this code, all will be spawned at one point, but why 0, 0, 0? Surely thats not right!
Oh, I got it. In the Awake() function, I didn't need to declare it was a Vector3 again. So now, how would I go about spawning them at individual random points?
Answer by PaulUsul · Nov 26, 2012 at 06:39 PM
The trick is that the Random.Range generates random numbers every time you call it.
void Start()
{
int spawned = 0;
while (spawned < numToSpawn)
{
position = new Vector3(Random.Range(100.0F, 1000.0F), 70, Random.Range(100.0F, 1000.0F));
Instantiate(ammoDrop, position, Quaternion.identity);
spawned++;
}
}
This way a new position is generated every time before you spawn the object.
Answer by flaviusxvii · Nov 26, 2012 at 07:03 PM
Your variable "position" in Awake() is shadowing the data member "position" of the class.
Answer by Meltdown · Nov 26, 2012 at 06:40 PM
I'd suggest tagging all your spawnpoints with a tag called 'spawnpoint', then use GameObject.FindGameObjectsWithTag() to get all the spawn points in your scene.
Then use Random.Range() to choose one of those random spawn points in your scene to instantiate your game object at.
and how would you ensure that the same spawn point is not selected again?
You can store Id of last selected spawn point and generate new ids until you generate a different one.
Your answer
Follow this Question
Related Questions
Spawn object from Random Vector3 in array 0 Answers
Drop item from airplane 1 Answer
Random death instantiate? 1 Answer
Instantiate Prefab at random 1 Answer