- Home /
Check if object is Rigidbody .js
Hello guys,
I wanna know what's the term to check if the script object is Rigidbody or not.
i've tried this piece of code but, sadly, it doesn't work
if (gameObject.GetComponent (Rigidbody) == true) {
doStuff();
}
Thanks in advance.
Please don't swear, this is a G-Rated 'site. Alucard Jay
Answer by AlucardJay · Jul 26, 2013 at 11:48 PM
Store the reference in a temporary variable, then check if that variable is null
var rBody : Rigidbody = GetComponent( Rigidbody );
if ( rBody ) // same as writing if ( rBody != null )
{
DoStuff();
}
Thank you very much Alucard, and sorry for swearing ^^ also, how's Richard Belmont? he's doing fine?
I'm Hellsing, Integra is fine thanks. Well spotted, most people don't see it =]
Answer by Linus · Jul 27, 2013 at 07:10 AM
Rigidbody actually has a magic shotcut.
You can simply do this:
if(rigidbody){
Debug.Log('I have a rigidbody');
} else {
Debug.Log('I do not have a rigidbody');
}
You can access rigidbody on other objects through transformVar.rigidbody
This is correct, but I went with the code the OP had. It also helps to understand the gameObject-Component relationship when trying to access components that are not variables of gameObject.
No problem, just providing extra information. And if I recall correctly GetComponent is done when using transform.rigidbody, so if its used in Update() it should be copied to a variable like you did.
Absolutely! Lots of good information here for future readers =]
Thank a lot guys, it'll be very usefull in the future for me.^^