I’m trying to animate a UI Image using an animator. I found a technique to do this here: Boia Games: Reusing your Unity 2D in-game animations for UI/Canvas.
The Hierarchy and Inspector for the Image I’m trying to animate is here:
The code for the ImageCanvasAnimator script (which is pretty much the same as from the link above) is here:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ImageCanvasAnimator : MonoBehaviour {
// set the controller you want to use in the inspector
public RuntimeAnimatorController controller;
// the UI/Image component
Image imageCanvas;
// the fake SpriteRenderer
SpriteRenderer fakeRenderer;
// the Animator
Animator animator;
[SerializeField] Sprite sprite;
void Start() {
imageCanvas = gameObject.GetComponent<Image>();
fakeRenderer = gameObject.AddComponent<SpriteRenderer>();
// avoid the SpriteRenderer to be rendered
fakeRenderer.enabled = false;
animator = gameObject.AddComponent<Animator>();
// set the controller
animator.runtimeAnimatorController = controller;
}
void Update() {
// if a controller is running, set the sprite
if (animator.runtimeAnimatorController) {
sprite = fakeRenderer.sprite; // this assignment works
imageCanvas.sprite = fakeRenderer.sprite; // this assignment DOES NOTHING
}
}
}
It seems to me that maybe the problem is that if you have a UnityEngine.UI Image and you try to change it’s sprite to the .sprite of a Sprite, like so:
UnityEngine.UI image;
Sprite sprite;
...
image.sprite = sprite.sprite
it will not work. I can’t seem to make it work, so I don’t know.
Does anyone have any ideas on why this does not work?
Clearly, the variable named “sprite” in the script above is getting assigned based on the values in the Inspector (see screenshot):
They match. But the Image Component’s Source Image is still empty. So I don’t know what I’m doing wrong.



