Recoloring animated sprites [Solved]

Dear fellow devs!

We’re developing a 2D pixel art game for which we have a number of different generic NPCs. Each of these can stand and walk around. I built a spawner that creates the desired numbers of NPCs, each of which randomly moves around the level.

In the original spritesheets (sliced-up Multiple sprites), the NPCs’ skin is in grayscale, and their clothes are colored in a certain set of blue and green. What I’m trying to achieve is swap these colors at runtime, so people have different skin colors and wear different colors of clothes, each generating their own (not necessarily unique) combination.

So far, I’ve managed to do that with a script copying, changing and then replacing the sprite of the NPCs SpriteRenderer component. This works fine for non-animated assets. The issue with animated sprites is that I need to replace the original spritesheet of each respective animation with its color-swapped counterpart in the NPC’s Animator right when the NPC is created, i.e. in Start() or Awake(). I found a way to do that, but it required using UnityEditor, so I can’t use it, since I’d like to be able to make a build from the game.

Just to check if it generally works, I put the sprite swap function in LateUpdate(). This does work, however, it’s extremely unelegant and too performance-heavy. The game turns into a slideshow with as little as ten NPCs in the scene.

Before you guys suggest using a shader instead - do you think the desired result can be achieved via code? Thanks a lot in advance!

Edit: To clarify: By putting the sprite swap in LateUpdate(), it just uses the old Animator with all its original un-swapped sprites and overwrites them each frame with a newly created colorswapped version. That’s unsustainable, of course, so instead, I want to change the actual spritesheets the Animator makes use of when the NPC spawns.

I don’t have the full answer, but you can get texture from sprite and do per pixel changes based on the original colors and apply that texture for a target sprite. A lot more simple than a shader, but just one of many solutions.

In some more specific way: you can translate your sprite set per object to replace certain colors with others, in this case I suppose a little random.

To anyone in the future who has the same question: As of now (Unity 5.5.1f1), I don’t believe there is a way to do what I wanted without using UnityEditor or a shader. I had to learn the basics of shaders first and then managed to achieve the desired effect using this tutorial:

It includes a shader and a script; I changed the script a lot to suit my game, but depending on what you need, it might work “out of the box” for you.