Is it possible to define a variable of multiple types?
I have a class which contains a var "myRenderer". This class is used in the game and in the UI as well. "myRenderer" is meant to contain the renderer that belongs to the appropriate instance of that class, so that I can easily access the instances visuals.
Now there is the problem, that I 'visualise' (the only front-end manifestation of the class instances is via sprites) some instances inside the UI not the normal game, which forces me to use Images instead of SpriteRenderers.
I don't want to create a second class, that is identical to the existing one (except the type of the myRenderer var), just because I have visualised 5 instances of it inside the UI. I also would have to duplicate every method relying on that class accordingly.
Is there a better solution?
Why do you need to keep the the SpriteRenderer/Image reference if you are not doing anything graphic related inside your class?
I just replace the sprites. Didn't think that was a big deal.
Answer by cjdev · Feb 03, 2016 at 01:31 AM
If I understand what you're looking for correctly I think you could just use a generic method to get your variable. If it's a variable of a type that inherits from Component, as I believe SpriteRenderer and Image do, then both types can be stored there and the generic method will return it back with the type specified, much like the GetComponent method in Unity.
public class ContainerClass : MonoBehaviour {
public Component myRenderer;
public T GetMyRenderer<T>()
{
return (T)(object)myRenderer;
}
}
Answer by hexagonius · Feb 01, 2016 at 10:01 PM
It would work if there was a common base class, but unfortunately that's "object" and therefore not even capable of doing anything graphic related. I don't think there is a way since there's just no common behaviour.
What do you mean with common base class? The class itself doesn't do anything graphic related. The problem is just that I store the appropriate SpriteRenderer in a variable of the instance of that class, while I cannot assign a SpriteRenderer for every instance, since some have to be UI Images. I need to somehow take that into account.
I mean, I could add a second variable of type Image, but then I had always one unused variable and everytime I want to access the Image/SpriteRenderer, I would have to check first, which one applies.