- Home /
C# How to Check If a Gameobject Contains a Certain Component
Hi everyone, I want to check if a Gameobject contains a component such as a rigidbody. How exactly do you do that? I have been searching for an if statement that does that but I haven't found anything.
Answer by TheDarkVoid · May 12, 2013 at 01:51 AM
it's really simple
if(gameObjectToCheck.GetComponent<Rigidbody>() != null)
{
//do something
}
this function also returns that component you so can access the component using this.
A simpler way is to use the property
rigidbody directly:
if (gameObjectToCheck.rigidbody){
// object has a rigidbody
}
But not all components have dedicated properties (the CharacterController is an example) thus using GetComponent is more versatile.
NOTE: These properties (rigidbody, audio etc.) have been deprecated in last Unity versions - now we must explicitly get any component but its transform via GetComponent (Unity did that behind the scenes anyway).
yes that will work for, lights, rigidbodies, transform, camera, audio sources, etc but not all, and for custom classes you will want to use GetComponent
How would I check if it doesn't contain a component? I have a script that adds a rigidbody to a gameobject and I want to check if that gameobject already has a rigidbody before the script adds it. I tried the if statement below but the script is still trying to add a rigidbody to the gameobject.
if(gameObject.GetComponent<Rigidbody>() == null)
that should work, does the gameobject have a rigidbody? does it get oned?
you're checking the current gameobject and not the target game obejct, you need to do if(playerCollider.gameObject.GetComponent() == null)
Answer by CozyBear · May 19, 2017 at 01:55 PM
For those stumbling upon this thread, I would not recommend the Best Answer's approach. Instead, use the following.
CustomComponent CC = this.GetComponent<CustomComponent>();
if (CC) {
//Component is valid AND stored for later use, preventing any further GetComponent calls
CC.value = 5;
}
if(!CC){
//Result is null, thus not attached. An 'else' following the previous block also works here.
}
Why? How does what you've done differ?
The accepted answer is fine if you only want to check if the component exists (which is what the question was asking for) and it mentions that the GetComponent function returns a reference to the component which can be used in the way that you do.
Frankly, this is ridiculous.
Actually, there's a good reason for NoonerBear's solution. Using GetComponent on a per-frame basis is not cheap, it allocates a fair bit of memory and if you call it every frame on several gameobjects. The memory allocation and de-allocation can have a noticable effect on your game. I work on a multiplayer game with 100 players and I see some pretty bad stuttering if I use Getcomponent on a per-frame basis (ie. inside of Update() ).
Sorry but no.
Neither his solution nor the accepted answer, nor the question, says anything whatsoever about doing anything on a per-frame basis.
Yes, if you need to do it every frame then you should cache the reference, but that's got nothing to do with the question. I can see some value to pointing it out as a comment to the accepted answer but it's not worth a new one, especially since it says nothing about why it's been written.
sorry, just trying to help.. I used to use Getcomponent liberally all over my code (most of the times in Update. I figure it'd be good advice to let people know the dangers of using it on a per frame basis, since it's probably not common knowledge that can hurt performance.
Why does it bother you that someone offers advice that is correct, and is related to the original question?
It's not like I was telling the original poster to go install Unreal engine, or something completely off topic
Answer by the_real_ijed · Mar 07, 2018 at 12:16 PM
This was my solution, which also goes beyond the scope of the question.
private Button buttonLocal;
public void Start()
{
buttonLocal = gameObject.GetComponent<Button>();
}
This assumes that you've got the component assigned to the game object and the code will fail if you try and use it later without anything being assigned. If you need that then you can use
if (localButton)
{
//do stuff
}
When you access it.
Answer by Euthyphro666 · Jun 25, 2020 at 02:47 AM
To add on to the answer given by CozyBear, you can do the same thing with cleaner syntax by using a simple extension method.
public static class Extensions
{
public static bool TryGetComponent<T>(this GameObject obj, T result) where T : Component
{
return (result = obj.GetComponent<T>()) != null;
}
}
That way you can check for the object and get a handle on the reference all in one go, like so:
if (gameObj.TryGetComponent<Component>(out var comp))
{
// Then you can use the component within this scope.
}
The benefit of this is that if you needed to have a whole bunch of these conditional blocks in a row, you wouldn't need the clutter of declarations or checks ahead of the conditionals. For example:
var comp1 = gameObj.TryGetComponent<Component1>();
var comp2 = gameObj.TryGetComponent<Component2>();
var comp3 = gameObj.TryGetComponent<Component3>();
if (comp1 != null)
{
// Do stuff
}
if (comp2 != null)
{
// Do stuff
}
if (comp3 != null)
{
// Do stuff
}
Versus
if (gameObj.TryGetComponent<Component1>(out var comp1))
{
// Do stuff
}
if (gameObj.TryGetComponent<Component2>(out var comp2))
{
// Do stuff
}
if (gameObj.TryGetComponent<Component3>(out var comp3))
{
// Do stuff
}
It may seem like a small enough difference, but it certainly can make things a lot nicer in certain situations.
No need for your extension method
https://docs.unity3d.com/ScriptReference/GameObject.TryGetComponent.html
Answer by Riiich · Sep 20, 2021 at 07:42 AM
If anyone is looking for "contains a certain component then use it", this is what you're looking for: TryGetComponent()
https://docs.unity3d.com/ScriptReference/GameObject.TryGetComponent.html
// The first way
if (gameObject.TryGetComponent(typeof(HingeJoint), out Component component))
{
component.name = "My Hinge";
}
// The second (and easier in my opion) way
if (gameObject.TryGetComponent(out Rigidbody rb))
{
rb.useGravity = true;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613102040im_/https://answers.unity.com/themes/thub/images/avi.jpg)