'Unity Instantiate bug
I’ve created a script that should spawn enemies in some time, and it works perfectly. However, for some reason it shows errors, even then it spawns enemies like it should.
Code:
public class Spawner : MonoBehaviour
{
[SerializeField]
private GameObject[] meteors;
public GameObject meteor1;
private float TimeBetweenSpawns;
public float StartTimeBetweenSpawn = 1f;
public float MaxY = 4.0f;
public float MinY = -4.0f;
float yPos;
float MinTime = 1f;
float MaxTime = 5f;
private Vector3 spawnPos;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//ChangeSpawnTimes();
yPos = Random.Range(MinY, MaxY);
spawnPos = new Vector3(transform.position.x, yPos, transform.position.z);
int WhichMeteor = 0;
int WhichMeteorRandom = Random.Range(1, 10);
if(WhichMeteorRandom > 8)
{
WhichMeteor = 0;
}
else
{
WhichMeteor = 1;
}
Debug.Log(WhichMeteor.ToString());
if (TimeBetweenSpawns <= 0)
{
Instantiate(meteors[0], transform.position, transform.rotation);
//float Time = Random.Range(1f,5f);
TimeBetweenSpawns = 1f;
}
else
{
TimeBetweenSpawns -= Time.deltaTime;
}
}
private void ChangeSpawnTimes()
{
Debug.Log(Points.points);
}
}
If I try to add only 1 metor not an array, just creating GameObject
adding prefab to an inspector it again shows an error, but works as it should, i.e. it spawns enemies in a timely manner.
Instantiate(meteor1, transform.position, transform.rotation);
Where is my mistake?
Solution 1:[1]
Seems that you have an array in your code & you're trying to access one of its indexes that don't exist.
for example:
int[] r;
r[0] = 5
r[1] = 4;
// Error Happens Here
print(r[2]);
The error is because r[2]
is null & isn't defined. So the solution is to check if the index is not null before trying to access it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Matin mohammadi |