Random spawn Gameobject in area

Hi all, i was thought to how make random spawner , i want create srvival game but the problem how can i spawn animals and enemys in randomly position in area , thanks

Do this:

``````    private Vector3 Min;
private  Vector3 Max;

private  float _xAxis;
private  float _yAxis;
private  float _zAxis; //If you need this, use it

private Vector3 _randomPosition ;
public bool _canInstantiate;

private void Start()
{
SetRanges();
}
private void Update()
{
_xAxis = UnityEngine.Random.Range(Min.x, Max.x);
_yAxis = UnityEngine.Random.Range(Min.y, Max.y);
_zAxis = UnityEngine.Random.Range(Min.z, Max.z);

_randomPosition = new Vector3(_xAxis, _yAxis, _zAxis );
}

//Here put the ranges where your object will appear, or put it in the inspector.

private void SetRanges()
{
Min = new Vector3(2, 4, 0); //Random value.
Max = new Vector3(20, 40, 30); //Another ramdon value, just for the example.
}

private void InstantiateRandomObjects()
{
if (_canInstantiate)
{
Instantiate(gameObject, _randomPosition , Quaternion.identity);
}

}
``````

One way to do it is to use System.Random to generate an X and Y value (for area). If you want volume, you can use the same System.Random for a z value…

I’ve put code below where you can give it a minimum value and a maximum value for each coordinate. Call this function for X, and then Y. Then when you instantiate your object, put it in the x, y location and you are all set.

``````public float generateRandomFloat(System.Random random, int min, int max)
{
int val = random.Next(min, max);
float offset = (float)val;
return offset;
}
``````