- Home /
Any drawbacks to swapping the SpriteRenderer.sprite each frame instead of using Unity's animator or legacy animation?
Hiya. I've written my own code for animating background elements in my game. Not actually sure why I bothered now, it seemed easier at the time to do it this way, so that I could control the animation using coroutines. My script is probably going to have less of a performance hit than Unity's own animator, but what about compared to the legacy animation (if that's what making animations using the Animation window is?). Or another method? I searched around and found SpriteManager, but it's just a little bit too complex for me too work with, not to mention its in C# and I'm using Javascript.
Here's my coroutine:
public function PlayOnce() : IEnumerator
{
// PlayState is an enum.
playState = PlayState.PLAY;
while (playState == PlayState.PLAY)
{
// If the currentFrameIndex (int) does not exist in the current animation array (int[])...
if (currentFrameIndex >= currentAnimation.length)
{
playState = PlayState.STOP;
}
else
{
// Show the sprite of the current animation at currentFrameIndex
spriteRenderer.sprite = allSprites[currentAnimation[currentFrameIndex]];
}
// Get the next frame to play
GetNextFrame();
yield WaitForSeconds(1f / animFrameRate);
}
}
And here's that GetNextFrame function:
// Get Next Frame
private function GetNextFrame()
{
// Linear
// AnimStyle is an enum.
if (animStyle == AnimStyle.LINEAR)
{
currentFrameIndex += 1;
}
}
might add more AnimStyles at some point.*
The variables are all public and set in the inspector.
I've love to know if I'm wasting my time with this method or if there is actually some kind of performance gain? Or any other kind of benefit I haven't thought of from going about it this way?
Thanks very much!
Romano
It's a trade off like anything else :)
http://wiki.unity3d.com/index.php?title=Texture_swap_animator
I've used this great snippet to death; modified it for many different purposes. It never seems to impact my performance.
Well, there is the RA$$anonymous$$ cost of storing the multiple textures you will need (if you go that route) and the cost of swapping them in and out (which isn't really that high unless the textures are large).
Basically the approach is more effective with smaller* textures, but that applies to anything texture related :)
*I've tried this with 2k textures and it seems to be just fine.
Thanks for that, that's good news for me :) I don't plan on using multiple textures, just multiple sprites from the same texture.
I think that kinda answers my question? I suppose it's a little bit of an open one. But if you want to convert it I'll mark it correct. Thankyouverymuch!