Help with random spawning from just outside the game screen

Hello all, I am new to Unity and to the forums and decided to make my first post after struggling with this problem for a few days and exhausting all my strategic attempts.

I am trying to make a simple game where animals spawn randomly just outside the game screen and then run towards the player.

I thought the best way would be to make a Vector3 array to store my spawn points and then call it with Random.Range but I can’t seem to get it working. Apparently Random.Range only works with int variables but obviously my spawn locations are all Vector3 variables.

Here is the code I am currently working with for reference.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnManager : MonoBehaviour
{
public GameObject[ ] animalPrefabs;
public int animalIndex;
private float spawnRangeX = 20.0f;
private float spawnPosZ = 25.0f;
private float spawnDelay = 2.5f;
private float spawnInterval = 2.0f;
private Vector3[ ] totalSpawnPos = new Vector3[4];

// Start is called before the first frame update
void Start()
{
InvokeRepeating(“SpawnRandomAnimal”, spawnDelay, spawnInterval);
}

// Update is called once per frame
void Update()
{

}

void SpawnRandomAnimal()
{

int animalIndex = Random.Range(0, animalPrefabs.Length);
totalSpawnPos[0] = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), 0, spawnPosZ);
totalSpawnPos[1] = new Vector3(-spawnRangeX, 0, Random.Range(-spawnPosZ, spawnPosZ));
totalSpawnPos[2] = new Vector3(spawnRangeX, 0, Random.Range(-spawnPosZ, spawnPosZ));
totalSpawnPos[3] = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), 0, -spawnPosZ);

Instantiate(animalPrefabs[animalIndex], (totalSpawnPos = Random.Range(0, 3)), animalPrefabs[animalIndex].transform.rotation);
}
}

I would really appreciate some words of wisdom from the sages of game development to at least point me in the right direction, and hope I am able to finally scratch this coding itch soon!

Thanks in advance!

Not really. There’s an int and float version. Here’s the docs. As in the docs, the int version has a specifric behaviour in relation to the range.

Also, please note you should always use code-tags when posting code and not plain-text. You can also edit your post too.

You should also post your errors because your code doesn’t look correct at all.

Here’s an example of how to pick a random Vector3 out of an array using Random.Range():

    Vector3 chosenSpawnPoint;

    Vector3[] spawnPoints = new Vector3[] { new Vector3(1f, 1f, 1f), new Vector3(2f, 2f, 2f), new Vector3(3f, 3f, 3f) };

    void Start()
    {
        chosenSpawnPoint = spawnPoints[Random.Range(0, spawnPoints.Length)];
    }

Thank you for your replies!

I should have read through the forums more before making my first post, I will ensure to use code tags in the future.

Thanks again for the references and advice!!

1 Like