在 Unity 中根据另一个纹理更改纹理的颜色?

Change the colors of a texture based on another texture in Unity?

所以我尝试使用函数 GetPixels 基本上根据第一个(或源)纹理的像素颜色更改第二个纹理的颜色。

我没有尝试太多,我一直在寻找解决这个问题的方法或获取一些文档,但 Unity 脚本 API 相当混乱。

到目前为止,我得到了一个根本无法工作的伪代码,如果你们中的任何人能帮助让它工作,那就太好了。

var secondTexture = new Texture2D(width, height);
Texture2D source = sourceTexture;

var pixels = new Color[width * height];
for (var x = 0; x < width; x++)
{
   for (var y = 0; y < height; y++)
   {
            Color pixels2 = source.GetPixels(x, y);

            if(pixels2 == Color.white)
            {
              //Paint the pixels in secondTexture that match X and Y of sourceTexture with blue per example
              pixels[x + y * width] = Color.blue;
            }
            else
            {
             //Paint the rest of the pixels with black
             pixels[x + y * width] = Color.black;
            }
   }
}
secondTexture.SetPixels(pixels);
secondTexture.wrapMode = TextureWrapMode.Clamp;
secondTexture.Apply();
return secondTexture;

所以基本上,应该发生的是,每当 sourceTexture 的像素为白色时,第二个纹理中的像素将更改为蓝色,而当 sourceTexture 中的像素不是白色时,secondTexture 中的像素为黑色的。这或多或少是个想法,但我不断得到的东西与 sourceTexture 颜色是什么无关,我在第二个纹理中的所有像素都是黑色的。知道为什么吗?

GetPixels() returns 颜色数组。如果要获取单个像素的颜色,请改用 GetPixel() 。在您的代码中尝试将 Color pixels2 = source.GetPixels(x, y); 更改为 Color pixels2 = source.GetPixel(x, y);

更新 1: 尝试测试这段代码。非常适合我。

int width = 150;
int height = 150;
Texture2D secondTexture;
public Texture2D source; //texture for a test, add in inspector
public Renderer rend; //Object for a test, add in inspector

      void Start()

    {
      secondTexture = new Texture2D(width, height);

      var pixels = new Color[width * height];
for (var x = 0; x < width; x++)
{
   for (var y = 0; y < height; y++)
   {
            Color pixels2 = source.GetPixel(x, y);

            if(pixels2 == Color.white)
            {
              //Paint the pixels in secondTexture that match X and Y of sourceTexture with blue per example
              pixels[x + y * width] = Color.blue;
            }
            else
            {
             //Paint the rest of the pixels with black
             pixels[x + y * width] = Color.black;
            }
   }
}
secondTexture.SetPixels(pixels);
secondTexture.wrapMode = TextureWrapMode.Clamp;
secondTexture.Apply();

rend.material.mainTexture = secondTexture;
    }