Loading a Dynamic Sprite and Animating it...

So with my game, I want to make it modable by the end users, so with that in mind I’m putting all the graphics, etc… as files on disk.

I can load a single sprite easy enough and assign it to a game object.

            fileData = System.IO.File.ReadAllBytes(fileName);

            Image = new Texture2D(ImageWidth, ImageHeight, TextureFormat.BGRA32, false);
            Image.LoadImage(fileData);

I then later create the sprite on the game object as:

            renderer = gameObject.GetComponent<SpriteRenderer>();

            renderer.sprite = Sprite.Create(Image, rect, new Vector2(0.5f, 0.5f));

This issue I’m trying to overcome is if I have an image that contains multiple cells of an animated sprite.

So I have an image that has a 32 x 32 sprite. The Image might be 128 x 32 which would give me 4 frames of animation for the 32 x 32 sprite.

Basically, I would have an animation speed on my class, what frame it should be currently showing and a reference to the large image with all the frames.

Do I manually load the full image in, then create multiple images as a collection, or is there a more efficient way to do it in Unity with the single image?

Thanks!

No one is loading sprites from disk and animating them?

Damn, I have this exact question. How did you end up doing it?

Two approaches -

1. use a single sprite per texture plus shader animation
You’ll need to learn a bit of shadergraph but here’s the relevant node: Flipbook Node | Shader Graph | 6.9.2

Each different texture will require a you to produce a different material.

2. create many sprites out of the same texture
When using Sprite.Create instead of using a rect that covers the whole texture, you need to do Sprite.Create many times to produce a List for each different sprite at each different location. Then to animate you can cycle through the sprites over time.

For efficiency, it will really depend so it’s hard to say for a general case - and probably won’t matter much.

1 Like