- Home /
Correct way to destroy GameObject with UnitySteer Steering attached
What is the best way to destroy a GameObject with a Steering script attached to it?
For example, I have many Vehicles traveling along a path. When a Vehicle reaches the last node, OnArrive is called. OnArrive destroys the Game Object.
On Destroying, I get the following error:
MissingReferenceException: The object of type 'NPCVehicle' 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.
DetectableObject.get_Position () (at Assets/_Library/UnitySteer/Behaviors/DetectableObject.cs:58)
Vehicle.PredictNearestApproachTime (.Vehicle other) (at Assets/_Library/UnitySteer/Behaviors/Vehicle.cs:545)
SteerForNeighborAvoidance.CalculateForce () (at Assets/_Library/UnitySteer/Behaviors/SteerForNeighborAvoidance.cs:104)
Steering.get_Force () (at Assets/_Library/UnitySteer/Behaviors/Steering.cs:40)
Steering.get_WeighedForce () (at Assets/_Library/UnitySteer/Behaviors/Steering.cs:82)
AutonomousVehicle.FixedUpdate () (at Assets/_Library/UnitySteer/Behaviors/AutonomousVehicle.cs:84)
I've subclassed AutonomousVehicle, but it's not overriding any of the AutonomousVehicle or Vehicle methods.
I've attempted to do Destroy(o), Destroy(o, waitTime), and DestroyImmediate(o) on the gameObject.
[edited for grammar]
Answer by Bunny83 · Nov 06, 2011 at 02:41 AM
It doesn't seem to be a problem with the object itself. It seems that another object (or manager) still holds a reference to the object and accesses it's position without a null-check. I never worked with UnitySteer but from your stacktrace and the current source code (i've just downloaded) it seems that another nearby vehicle is referencing your vehicle via their "Radar"-system which actually uses Physics.OverlapSphere to get the neighbors for collision avoidance.
Usually Destroy is always delayed until the end of frame so such errors won't happen. Make sure you never ever use DestroyImmediate to destroy gameobjects or components at runtime. It's a function basically designed for use in the editor (or in some very rare cases at runtime).
If the problem persists, try to disable it first and then use Destroy with a small delay. It seems the neighbor-detection ignores deactivated objects.
Turns out you were exactly right about the Radar. The UnitySteer Radar has a field "Detect Disabled Vehicles". Setting this to false fixed all the $$anonymous$$issingReferenceExceptions.