Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 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
1
Question by kevinrocks_786 · Feb 03, 2016 at 01:06 AM · c#unity 5getcomponenttypegenerics

HasComponent

0 down vote favorite

So I am writing a method to check if a gameObject has a component.

Here it is:

 public static bool HasComponent (this GameObject obj)
 {
     return obj.GetComponent<T>() != null;
 }

And I'm using it like this:

 void Update()
 {

     if (Input.GetKey("w"))
     {
         if (gameObject.HasComponent<Rigidbody>())
         {
             print("Has a rigid body.");
             return;
         }

         print("Does not have rigid body.");
     }
 }

The gameObject does NOT have a rigid body but it is still printing that it does have.

Comment
Add comment · Show 2
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 Bunny83 · Feb 03, 2016 at 01:15 AM 0
Share

edit your question, replace your code with your actual code and format it as code. The generic parameters are missing because you haven't formatted your code as code.

You have to select your code in your post and press the "101 / 010" button at the top. See the user guide section "Posting Questions, Answers and Comments".

avatar image kevinrocks_786 Bunny83 · Feb 03, 2016 at 01:24 AM 0
Share

There done. $$anonymous$$ay you please help now

4 Replies

· Add your reply
  • Sort: 
avatar image
3

Answer by Bunny83 · Feb 03, 2016 at 02:07 AM

Well, i guess your method definition looks like this:

  public static bool HasComponent<T> (this GameObject obj)
  {
      return obj.GetComponent<T>() != null;
  }

in which case you run into a nasty edge case problem. In the past this definition wouldn't compile since GetComponent used to have a contraint on the generic parameter to only allow types derived from Component.

Unity seem to have changed the definition and removed the constraint. This allows us to also use interfaces which is great.

However in your case the problem (which only occurs in the editor btw) is, that the "!=" check in your generic method most likely does a "System.Object" comparison. When testing inside the editor GetComponent will always return an instance. However that instance usually pretends to be null. This is done by overloading the "UnityEngine.Object" "==" and "!=" operators. Since your generic method doesn't use that specific operator it actually sees that fake-null object which of course is not null.

The problem shouldn't occur in a built version of your game.

There are several ways to make it work inside the editor as well:

First, add a constraint to "Component":

  public static bool HasComponent<T> (this GameObject obj) where T : Component
  {
      return obj.GetComponent<T>() != null;
  }

this will make the generic method to use the overloaded operators. However doing so prevents you from using interfaces with your method.

Another way would be to simply do an "as-cast" to ensure the right type:

  public static bool HasComponent<T> (this GameObject obj)
  {
      return (obj.GetComponent<T>() as Component) != null;
  }

This should work with all cases.

Another one would be

  public static bool HasComponent<T> (this GameObject obj)
  {
      return obj.GetComponent(typeof(T)) != null;
  }

The System.Type version of GetComponent always returns a Component. Since you don't use the actual type it's not necessary to use the generic version.

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 kevinrocks_786 · Feb 03, 2016 at 02:11 AM 0
Share

than you very much

avatar image
0

Answer by Jaysta · Feb 05, 2016 at 04:30 PM

Try using if(Input.GetKeyDown("W"))

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 lucariolu3d · Jun 04, 2020 at 12:44 AM 0
Share

wtf- thats not what he asked for

avatar image
0

Answer by JoshuaMcKenzie · Feb 03, 2016 at 01:36 AM

the function definition is still missing the <T> in ..

 public static bool HasComponent (this GameObject obj)

plus you possibly want constraints too (which should prevent invalid calls like HasComponent<int>()) and have it also extend Component instead to let pretty much anything that has a GetComponent<T>() have this function too

  public static bool HasComponent<T> (this Component obj) where T:class
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 kevinrocks_786 · Feb 03, 2016 at 01:51 AM 0
Share

$$anonymous$$y apologies, I did declare it with a . But I still do not get what you meant. Here is my current code:

 public static bool HasComponent<T>(this GameObject obj) where T : class
         {
             return obj.GetComponent<T>() != null;
         }
avatar image
0

Answer by kevinrocks_786 · Feb 03, 2016 at 02:10 AM

So it worked perfectly when I replaced the

 where T : class
 
 //With
 
 where T : Component
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

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

83 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 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 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 avatar image avatar image

Related Questions

How to update UI image mid-game (Unity, C#) 2 Answers

How to make an abstract pseudo-singleton class 1 Answer

Meaning of .text 1 Answer

Has my project's data corrupted? Script keeps returning null but 20 minutes ago it wasn't? 1 Answer

Is it possible to use a variable as a Type? 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