using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManager : MonoBehaviour
{
public float SpawnRangeX = 9.7f;
public float SpawnPosY = 4f;
public GameObject[] EnemyPrefabs;
public float SpawnDelay = Random.Range(0, 1);
public int RandomNum;
public Vector3 SpawnLocation;
// Start is called before the first frame update
void Start()
{
SpawnEnemies();
}
// Update is called once per frame
void Update()
{
RandomNum = Random.Range(0,EnemyPrefabs.Length);
SpawnLocation = new Vector3(Random.Range(SpawnRangeX, -SpawnRangeX), 0, SpawnPosY);
}
private void SpawnEnemies()
{
Instantiate(EnemyPrefabs[RandomNum], SpawnLocation, EnemyPrefabs[RandomNum].transform.rotation);
}
}
![197603-error.png|1347x35](upload://qfucpJkHT0Ln03EAS7mhi1PGU6W.png)
@qarallax is correct in moving the random functions from Update() into Start(), as it would yield better performance, but the issue lies in the constructor for your SpawnDelay variable. Unity doesn’t like it when you try to give a freshly constructed variable a random range, so you’ll have to do it in Start() or Awake(). I’ve applied the relevant fixes to your code and recommend you compare it to the code you wrote to get better context, but here it is below!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManager : MonoBehaviour
{
public float SpawnRangeX = 9.7f;
public float SpawnPosY = 4f;
public GameObject[] EnemyPrefabs;
public float SpawnDelay;
public int RandomNum;
public Vector3 SpawnLocation;
// Start is called before the first frame update
void Start()
{
SpawnEnemies();
RandomNum = Random.Range(0,EnemyPrefabs.Length);
SpawnLocation = new Vector3(Random.Range(SpawnRangeX, -SpawnRangeX), 0, SpawnPosY);
SpawnDelay = Random.Range(0, 1);
}
// Update is called once per frame
void Update()
{
}
private void SpawnEnemies()
{
Instantiate(EnemyPrefabs[RandomNum], SpawnLocation, EnemyPrefabs[RandomNum].transform.rotation);
}
}
Try to put “RandomNum = Random.Range(0,EnemyPrefabs.Length);” in the start method instead of the update method. And make sure to put it before you call the spawnEnemies void. Right now you are changing RandomNum every frame.