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)
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