Search Unity

Generic Components...

Discussion in 'Scripting' started by the_lemur, Aug 29, 2015.

  1. the_lemur

    the_lemur

    Joined:
    Apr 3, 2013
    Posts:
    104
    Apparently generic components aren't a thing.. at least not without going through circles that make the code unreadable... but I can't find a good way to do this.

    I have a component controlling a UI selection display.. but I want to be able to reuse it for several different kinds of data.. so I would like to be able to assign a generic type to the underlying display data fetched.

    of course i could make the data a completely arbitrary type and then force a cast.. but that's not very good practice.

    even creating an interface doesn't seem to help because the interface itself would need to be generic. like associating an ICollection<T> with the list of displayed selections.. but there's that generic again.

    I can't get around this in any elegant way.
     
  2. jordan-anderson

    jordan-anderson

    Joined:
    Aug 5, 2013
    Posts:
    2
    have you got a code sample of what you're trying to achieve maybe i can help.
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Standard work around is to make the generic class as your base class, then inherit from it for each type you want to use.

    Code (CSharp):
    1. public class MyClass <T> : MonoBehaviour {
    2.     // All logic goes here
    3. }
    4.  
    5. // These classes are empty. Used only to attach to GameObjects.
    6. public class MyClassFloat : MyClass<float>{}
    7. public class MyClassString : MyClass<string>{}
     
  4. the_lemur

    the_lemur

    Joined:
    Apr 3, 2013
    Posts:
    104
    yeah Mormon I noticed that was being done in other places. I should probably give in and do it that way.
     
  5. the_lemur

    the_lemur

    Joined:
    Apr 3, 2013
    Posts:
    104
    as for jordan I guess I was a bit vague. the basic idea is when you have a lot of selections you can make from a UI, any element you select might be associated with an underlying data object that gets passed back to a listener object. but the data getting passed with the event could be any type that the listener wants.

    again, it's not a terribly big deal to just typecast it. i mean.. we did it in C all the time...
     
  6. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Your other option is to fake it with reflection and custom inspectors.
     
  7. the_lemur

    the_lemur

    Joined:
    Apr 3, 2013
    Posts:
    104
    I went ahead with the subclassing option. Untyped objects and typecasting would feel more natural but im trying to do things 'properly'