Search Unity

Check for Component via enum?

Discussion in 'Scripting' started by Chaosgod_Esper, Jan 28, 2015.

  1. Chaosgod_Esper

    Chaosgod_Esper

    Joined:
    Oct 25, 2012
    Posts:
    295
    Hi there..

    i want to check, if a GameObject has a specific Component attached. The user can choose from an enum, which Component is searched.

    The enum:
    Code (csharp):
    1.  
    2.   public enum UIScripts{
    3.      NGUILabel=UILabel,
    4.      NGUISprite=UISprite,
    5.      NGUIButton=UIButton,
    6.      NGUIToggle=UIToggle};
    7.  
    8. public UIScripts SearchForComponent;
    9.  
    Now, how can i ask if a GameObject has attached the component chosen in "SearchForComponent"?
     
  2. Sbizz

    Sbizz

    Joined:
    Oct 2, 2014
    Posts:
    250
    enum has ToString method. You could use "GetComponent(string)" to know if the gameobject has the component.
     
  3. Chaosgod_Esper

    Chaosgod_Esper

    Joined:
    Oct 25, 2012
    Posts:
    295
    Ah, thank you :)
     
  4. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    You can add extension methods to enums.
     
  5. Chaosgod_Esper

    Chaosgod_Esper

    Joined:
    Oct 25, 2012
    Posts:
    295
    Yes, but just Integers ^^

    With ToString(), i can check if GetComponent(enum.ToString()) != null
     
  6. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    I was thinking something like

    Code (CSharp):
    1. public static class Extensions
    2. {
    3.     public static Component GetComponent(this MyEnum myEnum, GameObject gameObject)
    4.     {
    5.         return gameObject.GetComponent(myEnum.ToString());
    6.     }
    7. }
     
  7. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    That might not work as written, I'm slightly puzzled as to the data type you are using for your backing. You may need to override ToString, or have some other method to convert your backing variable to the type of component.