【问题标题】:Change the colors of a texture based on another texture in Unity?根据 Unity 中的另一个纹理更改纹理的颜色?
【发布时间】:2019-08-18 12:12:35
【问题描述】:

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

我没有尝试太多,我一直在寻找方法来解决这个问题或获取一些文档,但 Unity Scripting 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 中的像素不是白色时,第二个纹理上的像素是黑色的。这或多或少是个想法,但是我不断得到的东西并不重要,sourceTexture 颜色是什么,我在第二个纹理中的所有像素都是黑色的。知道为什么吗?

【问题讨论】:

    标签: unity3d textures pixel texture2d


    【解决方案1】:

    GetPixels() 返回一个颜色数组。如果要获取单个像素的颜色,请改用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;
        }
    

    【讨论】:

    • 还是一样,所有像素都是黑色的:S
    • 所以是的,这很有效,但是做一些其他的测试它不适合我,我的意思是,如果我使用导入的纹理它工作正常,但我确实需要它与程序纹理源纹理,所以我认为问题在于它没有设置为可读,所以我无法访问该源纹理(程序纹理),如果是这种情况,你知道如何启用读写?抱歉 xD 我刚刚在某处看到程序纹理未设置为可读
    猜你喜欢
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 2013-02-08
    • 2023-03-11
    • 2016-11-07
    • 2020-05-04
    • 2011-10-04
    相关资源
    最近更新 更多