In my Unity project, I’m trying to make a feature which every 5 seconds, a random number will be generated, and if the number equals 6, an enemy will be spawned. I tried to generate the number with UnityEngine.Random.Range(1,7) but I kept getting the following error:
UnityException: RandomRangeInt is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour ‘spawnEnemy’ on game object ‘enemySpawn’.
This is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawnEnemy : MonoBehaviour
{
public GameObject enemyPrefab;
public float spawnEnemySpeed = 5.0f;
private float spawnTimer = 0.0f;
int rng = 0;
void Start()
{
rng = UnityEngine.Random.Range(1,7);
Debug.Log(rng);
}
void Update()
{
spawnTimer += Time.deltaTime;
if (spawnTimer >= spawnEnemySpeed && rng == 6)
{
Instantiate(enemyPrefab, transform.position, transform.rotation);
spawnTimer = 0.0f;
rng = UnityEngine.Random.Range(1,7);
Debug.Log(rng);
}
}
}
I cannot find solution to this problem, most of the sources I found said that write the code in Start()
and Awake()
, but did not work for me even if I commented the code in the Update
.
One of the source I found :
Hey there 🙂 in this current code nothing would throw that error right now, have you saved your changes and cleared console of previous errors?
Also, the current code isn’t doing what you you think it might, You are only running the update loop logic if the initial generated random value is 6.
here is how the current code should look instead:
public GameObject enemyPrefab;
public float spawnEnemySpeed = 5.0f;
private float spawnTimer = 0.0f;
int rng = 0;
void Start()
{
rng = UnityEngine.Random.Range(1, 7);
Debug.Log(rng);
}
spawnTimer += Time.deltaTime;
if (spawnTimer >= spawnEnemySpeed)
{
spawnTimer = 0.0f;
if (rng == 6)
{
Instantiate(enemyPrefab, transform.position, transform.rotation);
}
rng = UnityEngine.Random.Range(1, 7);
Debug.Log(rng);
}
}
Hope it helps :)