sturdyspoon / unity-movement-ai

A Unity library for common movement AI
MIT License
1.95k stars 280 forks source link

NearSensor and its dependent behaviors try to access rigidbodies that have been destroyed at runtime #5

Open SpaceToastCoastToCoast opened 7 years ago

SpaceToastCoastToCoast commented 7 years ago

Great library! I've adapted it to a 3d project with movement along the x and z axes and it's working beautifully--but there's a major oversight when it comes to rigidbodies that have been destroyed after being added to the NearSensor's hashset.

I tried implementing a solution within the NearSensor script to first check if the rigidbody exists and is enabled before adding to the hashset--but that didn't address the case in which rigidbodies are destroyed after being added (such as when an enemy is killed). Cohesion, Separation, VelocityMatch and CollisionAvoidance were still trying to access the destroyed rigidbody, throwing null exceptions every frame.

I would suggest, in NearSensor-dependent scripts, at the beginning of the foreach loop iterating over members of the rigidbody hashset, to make it first check if the rigidbody at this index is null before accessing it. When I added this check, there were no more errors.

(P.S. I'd be happy to submit a pull request if you'd like to see the various tweaks I made to add this library to my project!)