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!