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!

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.

Your variable “position” in Awake() is shadowing the data member “position” of the class.

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.