Replace one specific color in a Sprite

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By julkip

I was just wondering, if it was possible to replace one specific color in a Sprite. I’d like to have n NPCs walking around, everyone having a diferent shirt color. I don’t know in advance how many instances of this scene I will have, so I cannot prepare n sprites with different colors beforehand.
I would like to replace every pixel of one color, lets say #ffffff, with a different color, lets say #ababab, in the whole texture of the sprite.
I think modulate does not do what I want, because as far as I understand, it changes every color, and not just one.

:bust_in_silhouette: Reply From: Dlean Jeans

Add this shader to your Sprite:

shader_type canvas_item;

uniform vec4 origin:hint_color;
uniform vec4 new:hint_color;

void fragment() {
	vec4 current_pixel = texture(TEXTURE, UV);
	
	if (current_pixel == origin)
		COLOR = new;
	else
		COLOR = current_pixel;
}

You change change the colors inside Shader Param in the Inspector.

EDIT: There’s a shader here that can change multiple shadings of color to another: https://forum.godotengine.org/20926/changing-specific-color-in-a-sprite-using-shaders-in-godot-3