Constrain Generic to Specific Classes

If I have a function

T Function <T> (T script) where T: ??? { }

How do I constrain T to specific classes, such as accepting SpriteRenderers and Images?

I’m probably misunderstanding generics, is there another way to constrain a parameter of a function to multiple classes?

You could do sth like :

T Function<T, U, V>(T script) where T : V, U { } 

but T should have been derived from U and V… so this couldn’t be considered as useful. There is a more straightforward way of doing what you want. And it’s overloading method as you need:

SpriteRenderer Function (SpriteRenderer script){ }
Image Function (Image script){ }

etc.

Generics are a bit tricky. You can use any type as constraint. However the types allowed would be the class specified in the constraint or any derived class. Note that multiple generic constraints are not combined with “or” but with “and”. So all constraints you put on a type parameter have to be fulfilled at the same time. So it’s not possible to specify two different types as constraints since a a type can’t be a SpriteRenderer and MeshRenderer at the same time.

Note that generics are fully compiled at compiletime. So the code inside a generic method need to work with all types you are allowed to pass in as type parameter. A generic method without any constraints can’t do much since there’s almost no common ground. By applying constraints to the type parameter you essentially set up a “contract” so the compiler knows whatever type will be used will have these specifed things. The actual type binding is done dynamically at runtime. That’s why the code need to compile with all acceptable types.

Your usecase isn’t quite clear. If you just want to prevent a method from being fed a wrong type this can only be done with runtime checks unless the types you want to use have a a common basclass

You can restrict T to a base class of a given type.

I believe most have Component as base class you could do where T : Component