Search Unity

Wrapping Generics in Generics

Discussion in 'Scripting' started by ToshoDaimos, May 23, 2019.

  1. ToshoDaimos

    ToshoDaimos

    Joined:
    Jan 30, 2013
    Posts:
    679
    I would like to have a custom wrapper on AddComponent method. I would like to do something like AttachScript<T>() call instead of AddComponent<T>. However, last time I checked it isn't so easy. Basically I would like to pass "T" parameter from an outer generic into the inner generic: AttachScript<T>() into AddComponent<T>(). How can I do it?
     
  2. grizzly

    grizzly

    Joined:
    Dec 5, 2012
    Posts:
    357
    You'll need to constrain your method;
    Code (CSharp):
    1. void AttachScript<T> () where T : Component
    2. {
    3.     gameObject.AddComponent<T>();
    4. }
     
    ToshoDaimos and Antistone like this.