Additional logic with adding Rigidbodys

I have used different assets than what Rick used. I encountered a few things that I thought I’d share.

First, my enemy assets already had mesh colliders on them. For these objects, no rigidbody is needed to detect a particle collision.

Second, if an enemy object already had a rigidbody, my script threw an error.

Also, it appears you don’t need to cache the rigidbody before turning off gravity. I was able to do it on the same line.

To address all of these issues, I wrote my AddRigidbody method like this:

    void AddRigidbody()
    {
        var meshCollider = this.GetComponent<MeshCollider>();
        var existingRb = this.GetComponent<Rigidbody>();
        if (!meshCollider && !existingRb)
        {
           gameObject.AddComponent<Rigidbody>().useGravity = false;
        }
    }

Basically
Get the current rigidbody
Get the current mesh collider
If both of those return nothing, add a rigidbody and set the gravity to false.

Privacy & Terms