Search Unity

Check if a GameObject has a certain script

Discussion in 'Scripting' started by zoultrex, May 7, 2011.

Thread Status:
Not open for further replies.
  1. zoultrex

    zoultrex

    Joined:
    Mar 11, 2010
    Posts:
    63
    I want to make a function to see if a gameObject has a certain script attached.

    I remember seeing some time ago how to pass a reference of any type, it was something with T or <t>, I'm quite sure this is something to do with Collections, but I am a bit confused about it and cant remember how to work with it.
    Maybe thats not even the best approach so any advices are of great help =]

    Here is part of the function that I will use to get the components attached to the gameObject and check if one of the components is of the same type as the class of the script I am looking for

    Code (csharp):
    1.  
    2.     public static bool HasComponent(GameObject obj, TheScriptClass scriptClassParam)
    3.     {
    4.         Component[] cs = (Component[])obj.GetComponents(typeof(Component));
    5.         foreach (Component c in cs)
    6.         {
    7.             Debug.Log("name " + c.name + " type " + c.GetType() + " basetype " + c.GetType().BaseType);
    8.            
    9.             //this part is where I want to check with the class that was passed to the function as a parameter
    10.             if (c.GetType() == scriptClassParam)
    11.             {
    12.                 return true;
    13.             }
    14.  
    15.         }
    16.         return false;
    17.     }
    18.  

    Oh btw, can anyone tell me if a for each loop any faster or slower then the GetComponent<type>() function?

    Thanks :D
     
  2. CoatlGames

    CoatlGames

    Joined:
    Apr 25, 2008
    Posts:
    773
    if you know exactly what type of component you want to check if its there, why not something really simple like

    JS
    if(gameObject.GetComponent("YouDesiredScript") != null)

    C#
    if((gameObject.GetComponent("YourDesiredScript") as YourDesiredScript) != null)

    i have used that simple method for finding out if a specific object has a specific script attached

    hope this helps
     
  3. zoultrex

    zoultrex

    Joined:
    Mar 11, 2010
    Posts:
    63
    Hi Hermes, gracias por tu respuesta

    I know this is very similar to the GetComponent<Script>() , I also use the GetComponent function sometimes.
    The reason I want to do this is because I want to expand my function to check multiple scripts at once passing a String array in another variation of this function, this one is just one of the helper functions I am creating.

    There will be different variations of this function with other parameters, but the base of it is the same as GetComponent that checks if there is a certain script attached.


    I found a way to do that, the base of the function is below, if anyone is interested in doing something similar one day here you go:

    Code (csharp):
    1.  
    2.     public static bool HasComponent(GameObject obj, Type ClassType )
    3.     {
    4.         Component[] cs = (Component[])obj.GetComponents(typeof(Component));
    5.         foreach (Component c in cs)
    6.         {
    7.  
    8.             if (c.GetType() == ClassType)
    9.             {
    10.                 return true;
    11.             }
    12.  
    13.         }
    14.         return false;
    15.     }
    16.  
    and to call the function:

    Code (csharp):
    1. HasComponent(MyGameObject,Type.GetType("Enemy")
    Where MyGameObject is the gameObject on the scene that I want to check, and the "Enemy" is the name of the class and script that is attached to it that I want to check
     
    angelo90 and yosefrow like this.
  4. akiel123

    akiel123

    Joined:
    Nov 18, 2013
    Posts:
    7
    Kinda late, but I'm trying to solve this too. When I use your method I get a MissingComponentException if it doesn't have the component, and I would like to avoid this. Is there any way to do that?
     
  5. akiel123

    akiel123

    Joined:
    Nov 18, 2013
    Posts:
    7
    Nevermind, did

    if(gameObject.GetComponents<YourDesiredComponent>().Length != 0)

    Instead :)
     
  6. A.Killingbeck

    A.Killingbeck

    Joined:
    Feb 21, 2014
    Posts:
    483
    Code (CSharp):
    1. using System.Linq;
    2.  
    3. public static bool HasComponent<T>(this GameObject go) where T : Component
    4.         {
    5.             return go.GetComponentsInChildren<T>().FirstOrDefault() != null;
    6.         }
     
  7. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    I don't understand why you would bother doing any of the stuff mentioned in this thread.
    Code (csharp):
    1.  
    2. SomeScript ss = GetComponent<SomeScript>();
    3. if (ss != null)
    4. {
    5.     DoGreatThings();
    6. }
    7.  
     
  8. KeinZantezuken

    KeinZantezuken

    Joined:
    Mar 28, 2017
    Posts:
    53
    ^it wont check if it is attached to specific GO though
     
  9. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Ok? So just ask that GameObject instead of the current one
    Code (csharp):
    1.  
    2. var script = someGameObject.GetComponent<SomeScript>();
    3. if (script != null)
    4. {
    5.  
    6. }
    7.  
     
  10. KeinZantezuken

    KeinZantezuken

    Joined:
    Mar 28, 2017
    Posts:
    53
    This will return exception if GO does not exist in the scene
     
  11. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,338
    No it won't. Also maybe don't necro three years old threads to complain about stuff that works?
     
    orb likes this.
  12. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    It will if the GameObject itself doesn't exist - but again, this is all standard stuff. Check if your thing is null before attempting to do something with it. Plain and simple, and none of the other solutions posted would resolve that issue either.
     
  13. KeinZantezuken

    KeinZantezuken

    Joined:
    Mar 28, 2017
    Posts:
    53
    Yes it will:

    A simple check returns exception if scene has no specified gameObject and IF your check is to check if go exist.

    That's the thing mate - if you try to check for null specific gO with specific Component and said gO does not exist in the scene - you are ded. All dies here.
     
  14. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Frankly I have absolutely no idea what you're talking about. If it is possible for a particular GameObject that you care about to be destroyed or otherwise become null during gameplay then you should null check it before operating on it.
     
  15. KeinZantezuken

    KeinZantezuken

    Joined:
    Mar 28, 2017
    Posts:
    53
    Even if it is not destroyed and active and in the scene. If an object has no component you request the nullref exception will be thrown in if{} REGARDLESS.
    Been over this for weeks had to resort to some custom functions for that
     
  16. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    No it doesn't. It only throws a NullReferenceException if you attempt to access something in that component without null checking it. If the GameObject is not null this will work all day long
    Code (csharp):
    1.  
    2. if (notNullGo.GetComponent<NullComponent>() != null)
    3. {
    4.     // if notNullGo is not null and it has no NullComponent attached this will never execute
    5. }
    6.  
     
    Bunny83, Kiwasi and cstooch like this.
  17. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Ummm. What? Are you trying to say null checking is broken? This kind of thing doesn't happen, this is entirely user error on your part. Here is a simple check if a component exists on a GameObject

    Code (CSharp):
    1. if(theGameObject != null && theGameObject.GetComponent<TheComponent>() != null){
    2.     // the component exists
    3. } else {
    4.     // the component does not exist
    5. }
     
  18. Schneider21

    Schneider21

    Joined:
    Feb 6, 2014
    Posts:
    3,512
    experts.PNG

    Which one of these people probably knows more about Unity...?
     
    orb likes this.
  19. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    This one just boils down to common sense. A null check throwing a null ref would be about the dumbest design decision this side of a screen door on a submarine.

    And honestly - RTFM. Right here: https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html

    null if it doesn't.

    If GetComponent returns null then that component isn't attached to the GameObject you're calling it on. That's how you determine if a GameObject has a specific component. Full stop. End of story.
     
  20. dev11223

    dev11223

    Joined:
    Feb 6, 2022
    Posts:
    3
    I think this is the most readable way to do the same

    Code (CSharp):
    1. if(SomeGameObject?.GetComponent<Desired_Script>())
    2. {
    3.     // SomeGameObject is not null and it has Desired_Script component.
    4. }
     
  21. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,929
    You should not use null conditional/propagating operators with UnityEngine.Object's. It bypasses the overridden
    ==
    operator they use.

    Seriously, it's 2023, we've had
    TryGetComponent<T>(out T)
    for years now.
     
Thread Status:
Not open for further replies.