I am trying to write a script that lets my animate either the Image or the SpriteRenderer component of a gameobject, depending on which of the two is attached. I’ve noticed that my logic works for both types, but I don’t know if and how it’s possible to convert a variable type depending on what kind of component my script finds in Awake.
Is it possible in C# to create some kind of Object variable and convert its type to whatever is attached to the gameobject? I’m trying something like this (pseudo code):
public Object myRenderingComponent; //can be Image or SpriteRenderer
void Awake() {
try
{
myRenderingComponent = GetComponent<Image>();
}
catch (myRenderingComponent == null)
{
myRenderingComponent = GetComponent<SpriteRenderer>();
}
catch (myRenderingComponent == null)
{
Debug.Log("Please attach an Image or SpriteRenderer component!");
}
}
void Update() {
//do my rendering code
myRenderingComponent.enabled = true;
myRenderingComponent.sprite = SetMyCurrentFrame();
//...
}
But in your Update(), call a method similar to this:
void SetFrame(Component renderingComponent) {
if (renderingComponent is SpriteRenderer) {
var spriteRenderer = renderingComponent as SpriteRenderer;
spriteRenderer.enabled = true;
spriteRenderer... //(set your other SpriteRenderer-specific stuff here)
} else if (renderingComponent is UnityEngine.UI.Image) {
var image = renderingComponent as UnityEngine.UI.Image;
image.enabled = true;
image... //(set your other Image-specific stuff here)
}
}