Hello, I am pretty new to Unity and am running into something that I can't figure out.
There are a few parts of my code that randomly causes a NullReferenceException.
They all involve using FindGameObjectsWithTag and then running a for loop through the array and doing something. For example:
landedPlatformNumber = collision.gameObject.GetComponent ().platformNumber;
GameObject[] platforms = GameObject.FindGameObjectsWithTag ("Platform");
for (var i = 0; i < platforms.Length; i++) {
if (platforms [i].GetComponent ().platformNumber < landedPlatformNumber) {
platforms [i].GetComponent ().DropPlatform ();
}
}
What is happening is the player is jumping up off a platform onto a higher platform. When the player lands on a platform the game removes the platforms below the one you landed on. This bit of code is called when you land on a platform. The script is part of the player gameobject.
The thing is, this normally works perfectly. But every now and then, for no reason that I can figure out (even when I haven't changed the code at all) I get the NullReferenceException. The frustrating thing is that while I try to figure out what the problem is, it will randomly fix itself and the errors no longer show up. Or I can restart unity and then it works again, even though I don't change anything in the code!
Please let me know if there is a something that I can do to fix this - I assume there's something obvious in my code that is incorrect or I am using something in the wrong way.
Thank you!
↧