Changing some color of a texture using C# in Unity

Changing some color of a texture using C# in Unity

It's almost 2 days that I'm looking for a way to do this in Unity using C#, but still no luck.
Imagine you have a texture with different colours (this texture can be a rug), and you just want to change the colour of the parts that you click on it. e.g. I click on blue and the blue part turn into yellow. take into consideration that the parts we click on it are irregular.
The images are png, but created in Photoshop using different layers. for example, in the following texture, we have 2 colours of pink and purple. if I click on purple I want it to become yellow, and if I click on pink I want it to become green 
How can I do it in Unity C#?
Thanks for all your helps. 


Answer 1:

You actually have two problems here. Problem A: how do I find image pixels to change? Problem B: how do I change specific pixels in Unity with C#?

As it happens, problem B is straightforward: you use Texture2D.GetPixels to read an array of pixel colors, change those colors and call Texture2D.SetPixels, followed by Texture2D.Apply. A couple caveats: first, make sure the texture in question is readable (i.e. it has “Read/Write Enabled” checkbox set in import settings). Second, this method is quite slow, and can cause a noticeable hitch with a large-ish texture. The faster way is to work with shaders.

Problem A is harder to solve, especially since you don’t state your requirements here. When you click on blue, do you need to change all blue pixels, or a region of blue pixels? Do you need to change exact color, or do you handle halftones and transitions too? And if so, how do you handle them?

The most trivial case is when you just switch all pixels of an exact color. Then you can just go

var colors = myTex.GetPixels();
for(int i=0; i<colors.Length; i++)

Answer 2:

Make each of these coloured blobs a seperate gameobject with a spriterenderer. Have the blobs saved as white or grayscale only.

Then, just apply the color you want in your SpriteRenderer. It will draw that blob at whatever color you want, and you can easily change the color programatically.

entity.GetComponent<SpriteRenderer>().color = new Color(0.5f, 0.5f, 0.1f, 1);