Search Unity

find out if GameObject has a compenent?

Discussion in 'Editor & General Support' started by yuriythebest, Jan 8, 2010.

  1. yuriythebest

    yuriythebest

    Joined:
    Nov 21, 2009
    Posts:
    1,125
    is there a way to check via code if a GameObject has a component (if a component exists for that GameObject)?
     
  2. HiggyB

    HiggyB

    Unity Product Evangelist

    Joined:
    Dec 8, 2006
    Posts:
    6,183
    Yup, GetComponent(). If the game object has the component then a reference to it is returned, if not then null is returned. Done! :)
     
    szymonisd and andyalexnf like this.
  3. yuriythebest

    yuriythebest

    Joined:
    Nov 21, 2009
    Posts:
    1,125
    thanks mister!
     
  4. RedVonix

    RedVonix

    Joined:
    Dec 13, 2011
    Posts:
    422
    Here's a weird one... I'm doing this exact check, but receiving an error that I need to do this check. :D

    Here's my code:

    Code (csharp):
    1.  
    2. if(gameObject.GetComponent<TouchInputAgent>() == null)
    3.     return;
    4.  
    With that code, the following error periodically occurs on the line that does the null check (maybe one out of every 4 times) whenever the object containing this component is destroyed from the world:
    Any thoughts on what could be happening there?
     
    tokar_dev, DTFun and alext621 like this.
  5. FuzzyQuills

    FuzzyQuills

    Joined:
    Jun 8, 2013
    Posts:
    2,871
    I have an even weirder case: I have two scripts to control the players in my game, one is for the user, one controls CPU slots. What i want to do is sort an array of objects where the possibility of both scripts showing up is 50/50. how do i get the right component so that the returned value is correct?
     
  6. MattRix

    MattRix

    Joined:
    Aug 23, 2011
    Posts:
    121
    I know this is super old, but I thought this might help someone:

    Your issue is due to Unity overriding the '==' operator. They use this to make objects act as null before they are *really* removed/null. See here for more info: http://blogs.unity3d.com/2014/05/16/custom-operator-should-we-keep-it/

    The solution in your problem would be to use ?? or Equals()
     
    Last edited: Sep 17, 2014
    e2000, droolz and guilhermecorintho like this.