I have the following function in my script. Unity throws the following error:
MissingReferenceException: The object of type 'UnityEngine.GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.
I don't understand why I'm getting the error as I'm removing the object from the list before destroying it.
float chunkLength = 10f;
void Update()
{
MoveChunks();
}
void MoveChunks()
{
// move each chunk in the chunk list backwards
for (int i = 0; i < chunksList.Count; i++)
{
chunksList[i].transform.Translate(-transform.forward * (chunkSpeed * Time.deltaTime));
// destroy the chunk if it goes behind the camera
if (chunksList[i].transform.position.z <= Camera.main.transform.position.z - chunkLength)
{
chunksList.Remove(chunksList[i]);
Destroy(chunksList[i]);
}
}
}
You are trying to destroy the wrong object.
Let's say you want to destroy the 5th element of the list, after you remove it, the 6th element will become the 5th, so you are actually trying to destroy the 6th element. What you need to do is store the gameObject in a temporary obj and then destroy this temporary obj.
Also you need to decrease the value of your iterator after you delete a object from the list.
GameObject tmp = chunksList[i];
chunksList.RemoveAt(i);
Destroy(tmp);
i--;