Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
15
Question by Ochreous · May 12, 2013 at 01:48 AM · c#componentif statement

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.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

6 Replies

· Add your reply
  • Sort: 
avatar image
42
Best Answer

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.

Comment
Add comment · Show 9 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image aldonaletto · May 12, 2013 at 01:56 AM 1
Share

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

avatar image TheDarkVoid · May 12, 2013 at 02:06 AM 0
Share

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

avatar image Ochreous · May 12, 2013 at 02:07 AM 0
Share

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)
avatar image TheDarkVoid · May 12, 2013 at 02:11 AM 0
Share

that should work, does the gameobject have a rigidbody? does it get oned?

avatar image TheDarkVoid · May 12, 2013 at 02:32 AM 1
Share

you're checking the current gameobject and not the target game obejct, you need to do if(playerCollider.gameObject.GetComponent() == null)

Show more comments
avatar image
10

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.
 }


Comment
Add comment · Show 8 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Bonfire-Boy · Oct 30, 2017 at 12:00 PM 0
Share

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.

avatar image Gooseman_1977 · Nov 14, 2017 at 03:34 AM 4
Share

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

avatar image Bonfire-Boy Gooseman_1977 · Nov 14, 2017 at 10:08 AM 1
Share

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.

avatar image Gooseman_1977 Bonfire-Boy · Nov 14, 2017 at 04:02 PM 3
Share

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

Show more comments
avatar image
2

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>();
     }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image the_real_ijed · Mar 07, 2018 at 12:20 PM 0
Share

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.

avatar image
0

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.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Hellium · Jun 25, 2020 at 07:31 AM 1
Share

No need for your extension method

https://docs.unity3d.com/ScriptReference/GameObject.TryGetComponent.html

avatar image
0

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;
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
  • 1
  • 2
  • ›

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

27 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

C# Adding Components From Other Gameobjects 3 Answers

Null Reference Exception on instantiated object's script. 2 Answers

C# How to Check If a Gameobject's tag doesn't equal a Specific Tag 3 Answers

C# Throw GameObject Upon Mouse Click 1 Answer

Player lives script help 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges