c# - 更改精灵纹理像素会导致巨大的灰色正方形
问题描述
我有一个 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;
}
解决方案
修改纹理的像素后,必须调用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;
}
推荐阅读
- javascript - 为什么 Rxjs 在订阅回调中出错时取消订阅?
- ruby - 使用 Ruby 和 Bing Ads API v2.0 的任何示例?
- docker - 如何在docker中分配时区
- html - IE上的背景位置
- c# - Azure 函数 blob BlobPath 转为小写
- c++ - 如何在qt c++中使用QPainter在stackedwidget页面上绘制不同的几何图形,如圆形?
- html - 响应式 css 网格图像库
- reactjs - converter.json2csv(header) - 测试
- android - 如何在 Android 中收听所有传出的短信(API 20 到 28)
- c# - 自动映射器错误 - “没有为此对象定义无参数构造函数”