How to Check if a component Exists on a Gameobject.

Hey, I have the following code in a script i wrote:

RaycastHit2D raydata = Physics2D.Linecast (transform.position, dir );
	
		Vector3 limit ;
		if (raydata.distance > 0) {
			limit = raydata.point;
		
			if (raydata.rigidbody.gameObject.GetComponent<Attack> () != null) { //errors here
				raydata.rigidbody.gameObject.GetComponent<Attack> ().Health -= dmg;
			}
		} else {
			limit = dir;
		}

but on running, it throws a NullReferenceException at the indicated line, and i can’t figure out why.
(Attack is the name of a script i’m looking for in the gameobject)

I suspect whatever it hit didn’t have a rigidbody. You should get the gameObject through the collider instead.

if (raydata.collider.gameObject.GetComponent<Attack> () != null) { //errors here
                 raydata.collider.gameObject.GetComponent<Attack> ().Health -= dmg;
             }

Create a class to check component

using UnityEngine;
public static class hasComponent {
	public static bool HasComponent<T>(this GameObject flag)where T : Component{
		return flag.GetComponent<T> () != null;
	}
}

And use it as follows … For eg. you wanna check for Rigidbody

public Gameobject gameObjectToCheck;

void yourMethod(){
    gameObjectToCheck.HasComponent<Rigidbody>();
}

It will return true if it has that component otherwise false … Good Luck

RaycastHit2D raydata = Physics2D.Linecast (transform.position, dir );
Vector3 limit ;

if(raydata.transform != null && raydata.distance > 0)
{
	limit = raydata.point;
 
	Attack attack = raydata.transform.gameObject.GetComponent<Attack>();
 
	if (attack != null) 
	{ 
		attack.Health -= dmg;
	}
}	 
else
{
	limit = dir;
}

If you relly need to check the rigidbody exists just change the:

raydata.transform.

for the:

raydata.rigidbody.

If you have lot of colliders on map use layers.
:wink: