Gridwright Start for $1

Palette Swap in Unity: a Sprite Shader for Team Colours

Palette swap sprites in Unity 6: bake recolours as PNGs, or swap exact colours live with a small sprite shader and a JSON colour map. Settings and code.

Palette Swapper at work
Palette Swapper at work: New colours for any sprite or sheet.

Your knight walks, attacks and falls over in four directions, and the Animator plays all of it from one sprite sheet. Now player two needs a red knight. Set the SpriteRenderer's Color to red and Unity multiplies the whole sprite by it: the armour turns red, and so do the face, the outline and the whites of the eyes. Paint a red copy of the sheet instead and you have a second set of sprites, and every animation clip has to be pointed at them, frame by frame.

A palette swap changes only the colours you name. This guide does it in Unity 6 two ways: bake the recolours into new PNGs, or keep one sheet and swap the colours while the game runs with a small sprite shader. The planning (which ramp carries the team colour, why dark has to stay dark) is the same in every engine and is covered in How to palette swap sprites. This page is the Unity part.

Import the sprite so its colours stay exact

Both ways need Unity to draw the PNG's colours exactly as the file stores them. Select the PNG in the Project window and set these in the Inspector:

Top-Down Characters
Top-Down Characters: 16x16 top-down pixel art RPG characters: 4 directions, idle and walk animations, emotes. One of the 150 packs in Gridwright.
  • Texture Type: Sprite (2D and UI), with Sprite Mode set to Multiple for a sheet.
  • Filter Mode: Point (no filter). Bilinear blends neighbouring pixels into colours the sprite doesn't have.
  • Compression: None, on the Default tab. The compressed formats shift colours slightly, and then the shader below has nothing to match.
  • Max Size: at least the width and height of your sheet, so Unity doesn't shrink it.
  • Generate Mipmap: off.
  • sRGB (Color Texture): leave it on.

Press Apply when you're done.

Way 1: bake a PNG per team

With two or three variants, baking is the quickest route. The Palette Swapper does it in your browser:

Side-View Characters
Side-View Characters: 10 animated 32x32 pixel art heroes and enemies: run, jump, attack, hurt and death, left and right. One of the 150 packs in Gridwright.
  1. Drop in the sprite or the whole sheet. It lists every colour, darkest first, and shows the original next to the recolour.
  2. Lock the colours that stay, such as skin and eyes.
  3. Fit a palette from a .hex, .gpl or .pal file, or one of the ready ones such as Team red. Keep the shading is the mode for team colours.
  4. Press Keep this one and make another for each team, then download the zip. It holds every recolour as a PNG of the same size, a palette file for each, and a JSON map of which colour became which.

The recolours are the same size as the original and their transparency is untouched, so each one slices with the same settings as the original sheet.

The cost comes later, in the Animator. Each recolour is its own set of sprites, so each coloured character needs its own clips that point at its own frames. With many teams, or colours the player picks, the shader is less work.

Your game, looking finished

Every Gridwright asset pack, made to fit together, and all 44 tools for the fiddly work, with every new release, for $17 a month. Try it in your own game first: 3 days for $1 with every tool and up to 10 packs. Cancel any time.

Start: 3 days for $1 See everything it includes

Way 2: swap colours live with a sprite shader

With the shader you keep one sheet. Each pixel looks for its colour in a list and, when it finds it, draws the new colour instead. The Animator keeps changing frames on the SpriteRenderer as before, and the material recolours whichever frame is showing.

Save this as PaletteSwap.shader anywhere in your Assets folder:

Shader "Gridwright/Palette Swap"
{
    Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
    }

    SubShader
    {
        Tags
        {
            "Queue" = "Transparent"
            "RenderType" = "Transparent"
            "IgnoreProjector" = "True"
            "PreviewType" = "Plane"
            "CanUseSpriteAtlas" = "True"
        }

        Cull Off
        ZWrite Off
        Blend One OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            #define MAX_COLORS 32

            sampler2D _MainTex;
            float _ColorCount;
            float4 _FromColors[MAX_COLORS]; // the PNG's colours, 0-1, as the file stores them
            float4 _ToColors[MAX_COLORS];

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
                float4 color : COLOR;
            };

            struct v2f
            {
                float4 pos : SV_POSITION;
                float2 uv : TEXCOORD0;
                float4 color : COLOR;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.pos = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                o.color = v.color;
                return o;
            }

            float3 ToFileColour (float3 c)
            {
                return float3(LinearToGammaSpaceExact(c.r), LinearToGammaSpaceExact(c.g), LinearToGammaSpaceExact(c.b));
            }

            float3 ToLinear (float3 c)
            {
                return float3(GammaToLinearSpaceExact(c.r), GammaToLinearSpaceExact(c.g), GammaToLinearSpaceExact(c.b));
            }

            float4 frag (v2f i) : SV_Target
            {
                float4 c = tex2D(_MainTex, i.uv);
                bool gamma = IsGammaSpace();
                float3 fileColour = gamma ? c.rgb : ToFileColour(c.rgb);

                for (int k = 0; k < MAX_COLORS; k++)
                {
                    if (k >= _ColorCount) break;
                    if (all(abs(fileColour - _FromColors[k].rgb) < 0.002))
                    {
                        c.rgb = gamma ? _ToColors[k].rgb : ToLinear(_ToColors[k].rgb);
                        break;
                    }
                }

                c *= i.color;
                c.rgb *= c.a;
                return c;
            }
            ENDCG
        }
    }
}

How it works:

  • _FromColors and _ToColors hold up to 32 colours each. Unity doesn't show shader arrays in the material Inspector or save them with the material, so the script below sets them.
  • When a project uses the Linear color space, Unity converts an sRGB texture to linear values as the shader reads it, so #3a6b2e doesn't arrive as the numbers in the file. ToFileColour turns the value back into the file's colour before comparing, and ToLinear turns the new colour into linear values for drawing. In Gamma color space the shader skips both. The conversion functions and IsGammaSpace() come from Unity's UnityCG.cginc.
  • The 0.002 limit is about half of one 8-bit step (1/255), so #3a6b2e matches and its neighbour #3a6b2f doesn't.
  • The last lines multiply by the SpriteRenderer's Color and premultiply alpha for the Blend One OneMinusSrcAlpha line, so half-transparent edge pixels blend as before.
  • The pass has no LightMode tag. URP treats such a pass as SRPDefaultUnlit, which its 2D Renderer draws, and the Built-in Render Pipeline draws it as well. The shader is unlit, so 2D lights don't change the sprite.

The script that fills the lists from the colour map

The arrays can't be typed into the material, and 32 colour pairs by hand would be slow anyway. The Palette Swapper's zip has a <name>_colours.json that lists every colour of the sprite and what it became in each recolour. Put that file in your Assets folder (Unity imports a .json file as a TextAsset) and add this script as PaletteSwap.cs:

using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;

[RequireComponent(typeof(SpriteRenderer))]
public class PaletteSwap : MonoBehaviour
{
    const int MaxColors = 32; // the same number as MAX_COLORS in the shader

    [SerializeField] TextAsset colourMap;   // the _colours.json from the Palette Swapper's zip
    [SerializeField] string variant = "team_red";

    static readonly int CountId = Shader.PropertyToID("_ColorCount");
    static readonly int FromId = Shader.PropertyToID("_FromColors");
    static readonly int ToId = Shader.PropertyToID("_ToColors");

    Material material;

    void Start()
    {
        Apply(variant);
    }

    void OnDestroy()
    {
        if (material != null) Destroy(material); // Unity leaves the copy for us to clean up
    }

    public void Apply(string variantName)
    {
        // Each variant in the file looks like {"name": "team_red", "file": "...", "colours": {"#3a6b2e": "#7a1626", ...}}
        Match block = Regex.Match(colourMap.text,
            "\"name\":\\s*\"" + Regex.Escape(variantName) + "\"[^{]*\"colours\":\\s*\\{([^}]*)\\}");
        if (!block.Success)
        {
            Debug.LogError($"{colourMap.name} has no recolour named {variantName}");
            return;
        }

        var from = new List<Vector4>();
        var to = new List<Vector4>();
        foreach (Match pair in Regex.Matches(block.Groups[1].Value,
                     "\"(#[0-9a-fA-F]{6})\":\\s*\"(#[0-9a-fA-F]{6})\""))
        {
            string oldHex = pair.Groups[1].Value, newHex = pair.Groups[2].Value;
            if (oldHex == newHex) continue; // colours that stay, such as locked skin
            ColorUtility.TryParseHtmlString(oldHex, out Color oldColour);
            ColorUtility.TryParseHtmlString(newHex, out Color newColour);
            from.Add(oldColour);
            to.Add(newColour);
        }

        if (from.Count > MaxColors)
        {
            Debug.LogWarning($"{variantName} changes {from.Count} colours; raise MaxColors and MAX_COLORS to match");
            from.RemoveRange(MaxColors, from.Count - MaxColors);
            to.RemoveRange(MaxColors, to.Count - MaxColors);
        }
        int count = from.Count;
        while (from.Count < MaxColors) // always send the full length, so a longer recolour fits later
        {
            from.Add(Vector4.zero);
            to.Add(Vector4.zero);
        }

        material = GetComponent<SpriteRenderer>().material; // this sprite's own copy
        material.SetFloat(CountId, count);
        material.SetVectorArray(FromId, from);
        material.SetVectorArray(ToId, to);
    }
}

Then set it up:

  1. Create a material and choose Gridwright > Palette Swap in its Shader menu.
  2. Drag the material onto the SpriteRenderer's Material slot.
  3. Add the Palette Swap component, drop the JSON on Colour Map and type the recolour's name in Variant.

The name is the one the JSON lists. When you fitted a palette it is the palette's name in lower case with underscores (Team red becomes team_red). Otherwise it is variant_1, variant_2 and so on, or recoloured if you downloaded without pressing Keep.

A few things the script takes care of:

  • GetComponent<SpriteRenderer>().material gives each sprite its own copy of the material, so a red knight and a blue knight can start from the same material asset and still show their own colours. Unity leaves that copy for you to destroy, which OnDestroy does.
  • Colours that map to themselves, such as locked skin, are skipped and don't take up any of the 32 places.
  • The arrays always go in at the full 32 entries. Once a material has an array, Unity caps any longer array set later to the first length and ignores the extra entries.
  • To change team while the game runs, call GetComponent<PaletteSwap>().Apply("team_blue");.
  • For more than 32 changed colours, raise MAX_COLORS in the shader and MaxColors in the script to the same number.

We compiled the script against the engine library of Unity 6000.0 and the shader with the Direct3D compiler and the include files that ship with that editor.

What about a lookup texture?

A common alternative is a lookup texture. Each pixel of the sprite stores a palette index in its red channel, and the shader reads the real colour from a small palette strip. It needs no loop, so it suits sprites with many colours. The catch is that every sprite has to be converted to index colours first, and stay that way each time the artist edits it. The shader above works on the PNG as it was drawn, so the art stays editable in any pixel editor.

When the swap goes wrong

  • Nothing changes. Look in the Console: the script logs an error when the JSON has no recolour by that name. Then check that the SpriteRenderer's material uses Gridwright/Palette Swap.
  • Some pixels keep the old colour. Compression or Bilinear filtering changed them, so set Compression to None and Filter Mode to Point (no filter). If a single shade stays, it may have a near twin, such as #3a6b2e and #3a6b2f. Both show up in the Palette Swapper's list, so give both a new colour.
  • Every knight shows the same team. The colours went onto sharedMaterial, which all sprites using that material share. Set them through material, as the script does.
  • The sprite ignores your 2D lights. The shader is unlit. If the scene depends on 2D lights, bake the recolours with Way 1 and keep a lit sprite material.

Recolour the next team

Open the Palette Swapper, drop in your sheet, lock the skin and keep a recolour for each team. The zip gives you the PNGs for Way 1 and the JSON for the script above. The tool is one of 44 tools in Gridwright, alongside 150 asset packs whose characters are ready to recolour.

Your game, looking finished

Every Gridwright asset pack, made to fit together, and all 44 tools for the fiddly work, with every new release, for $17 a month. Try it in your own game first: 3 days for $1 with every tool and up to 10 packs. Cancel any time.

Start: 3 days for $1 See everything it includes