I have a script set up in my 2D game so if my player gets too close to a mine it explodes and spawns another object that can hurt the player. This is the script:
It works fine, if I get to close to the mine, it goes away and spawns a new orb that is scripted to hurt the player if it comes in contact with them. The problem is I get this error message for every update (so A LOT):
*MissingReferenceException: The object of type '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. miner.Update () (at Assets/miner.js:11) *
I'm still learning scripting so any help is greatly appreciated. I'm sure it's a small mistake that I'm just overlooking.
targetObj is declared at the top, as a public variable. I don't know if you've set that in the inspector, or if some other code sets it.
After Destroy(targetObj) is called, that variable still points to targetObj. Next time Update gets called, the first line references targetObj again. Unity is warning you that it's a reference to a destroyed object.
There are any number of ways you can fix this, but it depends on who sets targetObj and what it represents. For example, you could set it to null after destroying the object. Then, at the top of Update, you'd need to add logic to skip the proximity test if targetObj is already null. Or maybe you'd want to set it to point at some other target once the first one is gone.
answered Oct 26 '10 at 06:39 PM
You destroy targetObj. Therefore after the first time the if Block is executed there is no targetObj anymore. Consequently when you are calling
you receive the error
It tells you exactly what's wrong
answered Oct 26 '10 at 06:35 PM