You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SetPixel转SetPixels32后代码无法正常运行,请求排查解决

修复SetPixels32转换后的问题

先给你指出代码里的几个关键错误,再附上修正后的版本:

  • 目标数组索引计算错误:
    原SetPixel代码里用_templateDirtMask.width计算每行像素数,你新代码里误用了heightScreenRes——像素数组的索引规则是x + y * 宽度,必须替换成目标纹理的宽度值。

  • Brush像素索引硬编码错误:
    取brushPixels时你写了x + (y * 32),这是硬编码宽度为32,但原代码是遍历_brush.width,所以应该改成x + y * _brush.width,否则只要brush宽度不是32,就会取错像素。

  • 颜色混合逻辑不一致:
    原代码直接把两个g通道值相乘(结果范围0-65025,Color会自动截断到0-255),你新代码里先归一化再相乘再转255,完全改变了原逻辑,要保持一致的话直接相乘后转byte即可。

  • 索引边界判断错误:
    原代码判断data > 0,但数组索引从0开始,应该改成arrElement >= 0,否则会漏掉索引0的像素。


修正后的代码:

for (int x = 0; x < _brush.width; x++)
{
    for (int y = 0; y < _brush.height; y++)
    {
        // 修复:用目标纹理宽度计算索引
        int arrElement = (pixelXOffset + x) + ((pixelYOffset + y) * _templateDirtMask.width);

        // 修复:包含索引0的边界判断
        if (arrElement >= 0 && arrElement < dirtMaskArr.Length)
        {
            // 修复:用brush实际宽度计算像素索引
            Color32 pixelDirt = brushPixels[x + (y * _brush.width)];
            Color32 pixelDirtMask = dirtMaskArr[arrElement];

            // 修复:保持原颜色混合逻辑
            byte greenValue = (byte)(pixelDirtMask.g * pixelDirt.g);

            dirtMaskArr[arrElement] = new Color32(0, greenValue, 0, 255);
        }
    }
}

_templateDirtMask.SetPixels32(dirtMaskArr);
_templateDirtMask.Apply(false);

内容的提问来源于stack exchange,提问作者Newboy11

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:20:39