Generic function to access properties of the same name

Hi All,

I want to access the color property of both a UI image or TMP_Text object. The classes are unrelated so there is no interface i can use. Is it possible to do something along the lines of:

MyFunction<Image>(img);
MyFunction<TMP_Text>(text);
MyFunction<T>( T in)
{
   in.color = Color.Red;
}

Other than reflection, not really. And I’d recommend against using reflection.

This is the kind of thing that can be condense into a static utility method.

I figured it couldn’t be done easily. What about dynamic objects? Could they be used for this sort of thing?

It seems to me bad practice to have two identical methods accepting different types…

Having utility methods with different overloads isn’t bad practice. Overloading methods is a normal thing to do in C#.

Yes but this isn’t just an overload, its a copy paste of the entire method. Remember, TMP_Text and Image have no common interface for accessing color, they just so happen to have a property of the same name.

Thinking on it, you could have a method that takes a delegate used as a ‘setter’. Maybe both getter and setter delegates, if required.

I presume you’re doing something like lerping a colour?

1 Like

That’s a good idea, I’ll implement it that way.

The function is just to ‘pulse’ an image or some text via a coroutine, nothing complex. It just felt like there would be an elegant solution but sounds like not.

Thanks for the advice!