Can't change sprite when Animator component is attached?

I’m new to unity. Why is it that when i disable the animator component, I can change a sprite just fine with code like this:

GetComponent(SpriteRenderer).sprite = newSpriteOne;

However, when i enable the animator component, even if there is no animation active, this code no longer works. It doesn’t give any errors, just simply wont change the sprite.

I’ve noticed that when an animation is played, it will revert to the default sprite for the object when the animation is complete. Does this have anything to do with it? Is the animator somehow locking in the default sprite and only allowing the sprite to change via animation? If so, is there a way around this to allow or change default sprite when there is no animation active?

I found that for some situations you can just disable the animator and the sprite changes fine. Then just enable the animator before triggering it.

It depends on your situation if this will work. I found it works great for a prefab that just has a death animation (Like a shot exploding before its GO is destroyed)

It is possible that you have defined Sprite curve in your animation like given in the picture.

51619-animator-component.png

Once you removed this curve from animation you can change sprite with no issues, since then it is not going to override your sprite you specified in code at runtime.

Hope it helps!

Just wanted to add a +1 to NeverHopeless’ comment. Man this issue has thrown me for some black hole detours … but more often than not the issue is indeed that the sprite/image in question has been pulled into some Animation keyframe curve … and that makes some if not all related C# code work inconsistently. Ugh so annoying!

Anyhow - thanks @NeverHopeless

There is a better solution. Use this script - GitHub - RetryEntry/UnityAnimatorChangeSprite: This script will swap sprite of an active animator to another one with the same dimensions.
Please give thumbs up, cause I have spent two days searching through useless solutions like one that suggected.
If you have 15 gameobjects with 15 sprites in animation chain you will spend up to 225 loops every frame searching for sprites to swap to…
With such approach you CAN’T create for instance charactes with different clothes animated by one animator, cause you will spend 12000 loops every second on useless things like searching. With this script you will not spend time… It uses shaders. You can change it as you’l like, Just star please. I have spent two days… :confused: