How to check if colliding object have a specific script attached?

Hi :slight_smile:
I have a cannonball with a collider attached to it. That cannonball collides with different objects, some of the objects have a script attached “Health_Script”, and other objects is just colliders. I want (in a script attached to the cannonball) to check if the colliding object has a “Health_Script” attached.
The following code, works but brings the error message “NullReferenceException” when the colliding object either doesn’t have a rigidbody or a “Health_Script” attached.

function OnCollisionStay(collision : Collision){
	if(collision.rigidbody.GetComponent(Health_Script) != null){
		//actions actions
	}
}

My question is: Is it wrong that code in some cases brings error messages even though it’s working? In that case, what is the proper way to check if an object has a specific script attached to it?

  • Tore

Use tags.

if(collision.transform.tag == "Enemy")
{
     //do stuff.
}

Thanks!

Or straight forward:

function OnCollisionStay(collision : Collision){
    if(collision.transform.GetComponent(Health_Script) != null){
        //actions actions
    }
}

Keep in mind, not every game object with which a collision happens has a rigidbody, but all of them have a transform.

Yep, use tags or what you were doing but with a few checks…

function OnCollisionStay(collision : Collision)
{
    if(collider.rigidbody == null)
        return;

    var hs:HealthScript = collider.transform.GetComponent(HealthScript);
    if(hs == null)
        return;

    ...
}

Common sense would suggest tag should be a fair bit faster though :slight_smile:

Thanks, I guess you are right. I must admit that I wasn’t aware of tags existence :slight_smile:

Yup, that’s a better way of doing it if not using tags. Thanks for your time!