Search Unity

How to get a type from a String in order to be used in GetComponent<> ?

Discussion in 'Scripting' started by Kiupe, Aug 21, 2018.

  1. Kiupe

    Kiupe

    Joined:
    Feb 1, 2013
    Posts:
    528
    Hello guys,

    Is it possible to retrieve a type using a string that represent a fully qualified class name and pass it to GetComponent<> ? A tried different ways to do that but none of them did succeeded.

    Thanks
     
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,779
    Why you store types as string will be first question?
    You know this approach is begging for bugs.
     
    SparrowGS likes this.
  3. Fido789

    Fido789

    Joined:
    Feb 26, 2013
    Posts:
    343
    Use GetComponent(Type type) or GetComponent(string type) overloads.
     
    Joe-Censored likes this.
  4. Kiupe

    Kiupe

    Joined:
    Feb 1, 2013
    Posts:
    528
    I do not really store a type as a string. The real case scenario is that I want to call GetComponent on an object in order to retrieve a component that is the same type as another component which I have a reference to.

    To be precise what I have is :

    - an Unity.Object which is a Component
    - A GameObject

    I need to find the Component type and then be able to use this type to call GetComponent on the GameObject to find if it holds a component of that type.

    If I was talking about string is that because with a variable Type you can get a string that full represent a class name.

    Thanks
     
  5. AndersMalmgren

    AndersMalmgren

    Joined:
    Aug 31, 2014
    Posts:
    5,358
    GetComponent(this.GetType());
     
  6. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,779
    You really want to avoid using strings wherever possible.
    Try cache types in form of collection (array/list/dictionary etc), or use enumerator to make switch statement, to call relevant type.

    Strings are nightmare to debug. Specially when you star ramming things.