- Home /
Swapping sprite of game object that has an animator. (Unity 2017.3.1)
Hi everyone!
I have this project where you can create an object, but before it is placed in the game you have to choose one element for it, so when it is created it will use a "skin" of this element.
The idea is that it has a base white sprite and then, when the element is selected, the sprite is changed for the one of the element.
The Game Object also has an Animator because the object has different animations for it (creation, destruction, etc.) and this animations are sprite sheets.
The problem:
I have to change the sprite in the Sprite Renderer of the Game Object depending on the selected element. I'm doing this by code, but although it is changed at some point (I've checked it through debug) it will return to the original base sprite.
I know at this moment that when using the animator it is hard to change the sprite by code, but I have a couple of questions that I hope you can help me to solve:
Is creating a different state for each element ok? Is it inefficient?
Do you know a way to accomplish this without creating a state for each element?
I could try using Anima2D. Is fine to run sprite sheets through Anima2D? Would it be inefficient?
I've tried to turn the Animator component off, just to turn it on when an animation needs to run. By doing that the sprite swapping was a success, the problem is that I need to know the duration of the animation for this. I could write a constant or a variable in the editor, but I would like to do it by code because the time could change in latter versions of the game. But getting the duration of an animation isn't easy (or it hasn't been for me to find how to do it). I tried using:
float time = animator.GetCurrentAnimatorStateInfo(0).length;
At the end it always returned 0.166667. So I guess this isn't the right way to do it. Is there a way to do this?
Thank you and sorry for the long post!
Your answer
Follow this Question
Related Questions
Change sprite in a sprite renderer with an animation 0 Answers
Prefabs and multiple tilesets? 0 Answers
Gui Box - Texture - Spritesheet 0 Answers
How to increase sprite animation speed 2 Answers
2 Animation Clips, 1 Sprite 0 Answers