- Home /
Is it impossible to swap the Texture2D of a Sprite Renderer at runtime?
I have a sprite sheet that has been duplicated numerous times with various alterations to each sheet.
I created an Animator and about half a dozen animations using one sheet. But now it seems that even if I have identical sprite sheets, I can't simply swap the Texture2D at runtime, meaning I need to painstakingly create a separate animation for every single variation to my texture sheets. Sadly, sprite.texture is read-only.
Is there absolutely no way of doing this?
Answer by JasonB · Feb 20, 2014 at 07:18 AM
I spent all night coming up with this solution.
It's not elegant, but it achieves what I needed.
Since I'm not allowed to change a sprite's source texture at runtime, I decided to change the texture itself at runtime instead. Here's what I did.
I started with some sprite sheets, I'll rename them for this example.
Monster_Green
Monster_Blue
Monster_Red
Whichever one you based your animations off of, rename it to something more generic, and make a copy of it. I renamed the green one, and made a copy of it. You also need to move everything into the Resources folder, and I additionally moved them into a subfolder under Resources called Sprites. You should now have these.
Monster
Monster_Green
Monster_Blue
Monster_Red
Make sure these files are given read/write permission by changing them from Sprite to Advanced and checking the appropriate box. "Monster" is now going to chameleon the color data from whichever sprite sheet you want (as long as the sizes match). Here's the code for changing our monster sprite into the blue monster.
Color[] gotcolors = Resources.Load<Texture2D>("Sprites/Monster_Blue").GetPixels();
Resources.Load<Texture2D>("Sprites/Monster").SetPixels(gotcolors);
Resources.Load<Texture2D>("Sprites/Monster").Apply();
This code gets all color data from Monster_Blue and stores it in gotcolors. It then reassigns all color data to Monster to look like Monster_Blue. The reason we created Monster generic is this way we don't destroy any of our source sheets.
And so, using this method, you can do as many animations as your heart desires on just one sprite sheet, and then swap sheets to get different characters (as long as the sheets are of identical size and your characters are placed identically, as they are still sliced according to the original sprite sheet).
Here's what this doesn't solve. I only needed this on a character who (thankfully) exists on a unique basis. There's no way to do this to assign different sheets to different objects, since it alters the texture they all use and every instance would look identical (unless that's what you want). So the Unity team still needs to add texture swapping at runtime in an official capacity for sprite sheets, as my solution is hacky and not for everyone.
Hope this helps someone.
is there a new method of doing this, but not so hacky? it is 2016...