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

使用Texture2D.SetPixelData设置全红像素却出现杂色的问题

问题排查与修复方案

核心错误:Color值超出有效范围

Unity的Color结构体构造函数参数是**01的浮点数**(对应0255的整数色域),你传入255会导致颜色值溢出,GPU渲染时会将超出范围的数值异常处理,最终出现杂色或透明问题。

次要问题:纹理格式与数据类型不匹配

使用TextureFormat.RGB24时,SetPixelData<Color>会因为Color是四通道(RGBA)数据,而RGB24是三通道格式,导致数据错位,进一步加剧显示异常。


修正后的完整代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class TextureScript : MonoBehaviour
{
    Texture2D texture;

    void Start()
    {
        // 使用RGBA32格式适配Color的四通道数据
        texture = new Texture2D(256, 256, TextureFormat.RGBA32, true);
        var rectTransform = transform.GetComponent<RectTransform>();
        rectTransform.sizeDelta = new Vector2(texture.width, texture.height);

        int pixelCount = texture.width * texture.height;
        Queue<Color> queue = new Queue<Color>();

        // 用0~1的浮点数定义红色(alpha设为1保证不透明)
        for(int i = 0; i < pixelCount; i++)
        {
            queue.Enqueue(new Color(1f, 0f, 0f, 1f));
        }

        Color[] colorArray = queue.ToArray();
        // 直接使用SetPixels更直观,避免格式匹配问题(SetPixelData需要严格对应格式的字节布局)
        texture.SetPixels(colorArray);
        texture.filterMode = FilterMode.Point;
        texture.Apply(updateMipmaps: false);
        
        GetComponent<RawImage>().texture = texture;
        // 无需绕到material.mainTexture,RawImage直接赋值texture即可
    }

    void Update()
    {
    }
}

额外优化说明

  • 替换SetPixelData为SetPixels:SetPixels是专门为Color数组设计的API,自动处理纹理格式的通道匹配,比SetPixelData更易用且不易出错。
  • 直接给RawImage.texture赋值:无需通过material.mainTexture,RawImage本身提供了直接设置纹理的接口,更高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 09:45:08