- Home /
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)
Answer by flaviusxvii · Sep 12, 2016 at 04:45 AM
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;
}
You also should check if raydata.collider
is not null. That's the actual indicator if you hit something or not.
Answer by aditya · Sep 12, 2016 at 05:20 AM
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
Why would you use "GetComponents" which actually allocates an array on the heap with all components of that type? Just using GetComponent and doing a null check will do the same without any garbage creation.
Correct ... but it looks cool to just check for a true false value rather than a comparison with a value in an actual code ... but you know what, i didn't even noticed that GetComponents thing when posting here as this code was for my project and was according to my needs ... BTW a big thanks (AGAIN) as i m editing my answer ^^
Answer by Masterio · Sep 12, 2016 at 01:02 PM
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. ;)
Your answer
Follow this Question
Related Questions
How to add a component on a GameObject in Custom Inspector 1 Answer
How to get a component from an object and add it to another? (Copy components at runtime) 12 Answers
How do I nullreference this correctly? 1 Answer
NullReferenceException error in an array of objects 0 Answers
AddComponent() causes a "trying to create a MonoBehaviour using the 'new' keyword" warning 2 Answers