首页 > 解决方案 > 更改精灵纹理像素会导致巨大的灰色正方形

问题描述

我有一个 32x32 的精灵,我正在尝试访问和修改它的像素数据。

为此,我只需获取精灵的纹理,基于旧纹理创建新纹理,然后更改新纹理的像素值。然后我用修改后的纹理创建一个新的精灵,并将 SpriteRenderer 的精灵参数更改为新的精灵。

然而,当我实际运行我的脚本时,我得到的是一个巨大的灰色方块,很容易是原始 32x32 精灵大小的 10 倍。我对统一很陌生,所以我不确定为什么会这样。任何见解都会很棒。

    private Sprite sprite;
    private Texture2D texture;


    // Use this for initialization
    void Start ()
    {
        sprite = this.gameObject.GetComponent<SpriteRenderer>().sprite;
        texture = sprite.texture;
        Texture2D newTexture = modifyTexture(texture);

        SpriteRenderer sr = this.gameObject.GetComponent<SpriteRenderer>();
        sr.sprite = Sprite.Create(newTexture, new Rect(0, 0, newTexture.width, newTexture.height), new Vector2(0, 0), 10);
    }

    public Texture2D modifyTexture(Texture2D baseTexture)
    {
        Texture2D newTexture = new Texture2D(baseTexture.width, baseTexture.height);

        int x = 0;
        while(x < newTexture.width)
        {
            int y = 0;
            while(y < newTexture.height)
            {
                Color currentPixel = baseTexture.GetPixel(x,y);
                Color modifiedPixel = currentPixel;
                modifiedPixel.r = (float)(modifiedPixel.r + 0.10);
                modifiedPixel.b = (float)(modifiedPixel.b + 0.10);
                modifiedPixel.g = (float)(0.10);
                newTexture.SetPixel(x, y, modifiedPixel);
                y++;
            }
            x++;
        }

        Debug.Log(newTexture.GetPixel(5, 5).ToString());
        return newTexture;
    }

标签: c#unity3d

解决方案


修改纹理的像素后,必须调用Apply函数将修改后的像素上传到显卡。

public Texture2D modifyTexture(Texture2D baseTexture)
{
    Texture2D newTexture = new Texture2D(baseTexture.width, baseTexture.height);

    int x = 0;
    while (x < newTexture.width)
    {
        int y = 0;
        while (y < newTexture.height)
        {
            Color currentPixel = baseTexture.GetPixel(x, y);
            Color modifiedPixel = currentPixel;
            modifiedPixel.r = (float)(modifiedPixel.r + 0.10);
            modifiedPixel.b = (float)(modifiedPixel.b + 0.10);
            modifiedPixel.g = (float)(0.10);
            newTexture.SetPixel(x, y, modifiedPixel);
            y++;
        }
        x++;
    }
    //Upload changes to Graphics graphics card
    newTexture.Apply();

    Debug.Log(newTexture.GetPixel(5, 5).ToString());
    return newTexture;
}

推荐阅读