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

如何通过宽高调整Texture2D大小?遇索引越界及格式报错求解决

搞定Unity Texture2D的格式不兼容与索引越界问题

嘿,我来帮你解决这个头疼的纹理调整问题!你遇到的两个错误(索引越界+SetPixels32格式不匹配)其实是关联的,核心原因出在Texture2D.Resize方法的行为上。

错误根源拆解

你调用graphics.Resize(...)时指定了TextureFormat.RGBA32,但Unity在某些情况下(比如原纹理格式不兼容、平台格式限制)会自动降级到其他格式——错误里的TextureFormat(12)就是RGB24格式,这就导致后续调用SetPixels32(只支持RGBA32/BGRA32)时直接报错。另外,如果计算出来的宽高是负数或0,还会触发索引越界问题。

靠谱解决方案:直接新建纹理(推荐)

与其依赖容易出问题的Resize,不如直接创建一个完全符合要求的新纹理,彻底规避格式和尺寸的坑:

// 先计算目标宽高,务必确保结果是正整数!
int targetWidth = horizontalx - horizontaly;
int targetHeight = verticalx - verticaly;

// 先校验宽高合法性,避免索引越界
if (targetWidth <= 0 || targetHeight <= 0)
{
    Debug.LogError("目标宽高必须为正整数!");
    return;
}

// 销毁旧纹理(如果不需要保留的话)
UnityEngine.Object.Destroy(graphics);

// 新建严格指定RGBA32格式的纹理
graphics = new Texture2D(targetWidth, targetHeight, TextureFormat.RGBA32, false);
// 一定要调用Apply让修改生效
graphics.Apply();

备选方案:修复Resize后的格式问题

如果你坚持要用Resize,那必须在调用后校验格式,不匹配就手动转换:

int targetWidth = horizontalx - horizontaly;
int targetHeight = verticalx - verticaly;

if (targetWidth <= 0 || targetHeight <= 0)
{
    Debug.LogError("目标宽高非法!");
    return;
}

graphics.Resize(targetWidth, targetHeight, TextureFormat.RGBA32, false);

// 检查实际格式是否符合预期
if (graphics.format != TextureFormat.RGBA32)
{
    // 创建临时纹理转换格式
    Texture2D tempTexture = new Texture2D(targetWidth, targetHeight, TextureFormat.RGBA32, false);
    tempTexture.SetPixels32(graphics.GetPixels32());
    tempTexture.Apply();
    
    // 替换原纹理并清理临时对象
    UnityEngine.Object.Destroy(graphics);
    graphics = tempTexture;
}

额外注意事项

  • 永远先校验计算出的宽高是否为正整数,这是避免索引越界的关键。
  • 调用SetPixels32或修改纹理后,必须调用Apply()才能让修改同步到GPU。
  • 如果原纹理是从资源加载的(比如AssetBundle或Resources),可能是不可写状态,需要先调用graphics.SetPixels32(graphics.GetPixels32())解锁后再操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:13:56