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 :
Aucun commentaire:
Enregistrer un commentaire