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

Unity中Graphics.CopyTexture纹理类型不匹配错误(src=5 dst=2)排查

解决Graphics.CopyTexture纹理类型不匹配错误(src=5 dst=2)

这个错误的核心不是像素格式不匹配,而是纹理的维度/类型不匹配:

  • 错误中的src=5对应Unity的TextureType.Tex2DArray(也就是你的源Texture2DArray)
  • dst=2对应TextureType.Tex2D(你创建的普通Texture2D)

Graphics.CopyTexture的基础重载会默认尝试复制整个纹理资源的所有维度,但Texture2DArray是带有切片(depth)维度的二维数组纹理,普通Texture2D是二维纹理,两者维度不兼容,因此触发这个类型不匹配错误。

正确的解决方法

使用Graphics.CopyTexture的重载版本,明确指定要复制的Texture2DArray切片索引,将单个切片的内容复制到目标Texture2D中。示例代码如下:

using UnityEngine;
using System.Collections.Generic;

public class TextureArrayConverter : MonoBehaviour
{
    public Texture2DArray terrainTextureArray;
    public List<Texture2D> uiTextureList = new List<Texture2D>();

    void Start()
    {
        ConvertTextureArrayToList();
    }

    void ConvertTextureArrayToList()
    {
        if (terrainTextureArray == null) return;

        // 遍历Texture2DArray的所有切片
        for (int sliceIndex = 0; sliceIndex < terrainTextureArray.depth; sliceIndex++)
        {
            // 创建与切片匹配尺寸、格式、mipmap设置的Texture2D
            Texture2D targetTex = new Texture2D(
                terrainTextureArray.width,
                terrainTextureArray.height,
                terrainTextureArray.format,
                terrainTextureArray.mipmapCount > 1 // 是否包含mipmap
            );
            targetTex.filterMode = terrainTextureArray.filterMode;
            targetTex.wrapMode = TextureWrapMode.Clamp; // UI场景下建议用Clamp避免边缘拉伸

            // 关键:指定源切片索引进行复制
            // 参数说明:源纹理、源mipmap层级、源切片索引、目标纹理、目标mipmap层级、目标切片索引
            Graphics.CopyTexture(terrainTextureArray, 0, sliceIndex, targetTex, 0, 0);

            uiTextureList.Add(targetTex);
        }
    }

    // 记得在不需要时清理生成的纹理,避免内存泄漏
    void OnDestroy()
    {
        foreach (var tex in uiTextureList)
        {
            Destroy(tex);
        }
        uiTextureList.Clear();
    }
}

注意事项

  • 目标Texture2D的尺寸、像素格式、mipmap数量必须与源切片完全一致,否则复制会失败或出现异常
  • 如果你的Texture2DArray使用了压缩格式(比如DXT1),目标Texture2D也必须使用相同的压缩格式,不要强行转换为RGBA32,否则不仅会浪费内存,还可能导致复制失败
  • UI按钮使用这些纹理时,建议将Texture2D的wrapMode设为Clamp,避免纹理边缘出现重复拉伸的问题
  • 生成的Texture2D属于动态创建资源,记得在场景销毁或不再使用时调用Destroy()释放内存

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 08:42:10