Version: 2020.3

Texture2D.GetRawTextureData

切换到手册
public NativeArray<T> GetRawTextureData ();

返回

NativeArray<T> 原始纹理数据视图。

描述

从纹理中获取原始数据以进行读取或写入。

此函数将直接“视图”作为 Unity.Collections.NativeArray 返回到纹理像素数据中。

该数据根据其宽度、高度、数据.format和 mipmapCount 将是整个纹理。Mipmap 的内存布局是从最大级别开始,较小 Mip 级别的数据紧随其后。例如,没有 Mipmap 的 RGBA32 格式的 16x8 纹理将产生 512 字节的数组 (16x8x4) 或 128 元素的数组(如果使用的类型为 Color32)。

您可以读取和写入返回的数组。如果写入该数组,则必须调用 Apply 方法将纹理上传到 GPU。

GetRawTextureData 不分配内存;返回的 NativeArray 直接指向纹理系统内存数据缓冲区。

注意:如果在调用此方法后对纹理进行了修改或上传,则返回的数组可能无效(即,它不再指向有效内存)。因此,建议使用此方法的方式是获取数据,然后立即使用或修改它。不应存储返回的数组供以后使用。

See Also: Apply, SetPixels, SetPixels32, LoadRawTextureData, GetPixelData.

using UnityEngine;

public class ExampleScript : MonoBehaviour { void Start() { var texture = new Texture2D(128, 128, TextureFormat.RGBA32, false); GetComponent<Renderer>().material.mainTexture = texture;

// RGBA32 texture format data layout exactly matches Color32 struct var data = texture.GetRawTextureData<Color32>();

// fill texture data with a simple pattern Color32 orange = new Color32(255, 165, 0, 255); Color32 teal = new Color32(0, 128, 128, 255); int index = 0; for (int y = 0; y < texture.height; y++) { for (int x = 0; x < texture.width; x++) { data[index++] = ((x &amp; y) == 0 ? orange : teal); } } // upload to the GPU texture.Apply(); } }

public byte[] GetRawTextureData ();

返回

byte[] 原始纹理数据的字节数组。

描述

从纹理中获取原始数据。

该函数将原始纹理数据以字节数组的形式返回,以便您可以使用 Texture2D.LoadRawTextureData 进行加载。这让您能够序列化和加载任意格式(包括压缩格式)的纹理,并稍后重新将它们加载到纹理中。

Note that this function returns Unity's system memory copy of the texture data, so for it to work Texture.isReadable must be true.

另请注意,系统内存副本可能与当前 GPU 纹理数据中的内容不匹配。例如, 在调用 SetPixels 后,系统内存副本已修改, 但只有在调用 Apply() 后,GPU 副本才会匹配。对于某些 Graphics.CopyTexture,可能只复制 GPU 纹理部分 (例如从 RenderTexture 复制到 Texture2D),这不会反映在 GetRawTextureData 内容中。

using UnityEngine;

class CopyTexture : MonoBehaviour { // the source texture. Texture2D tex;

void Start() { // Create a copy of the texture by reading and applying the raw texture data. Texture2D texCopy = new Texture2D(tex.width, tex.height, tex.format, tex.mipmapCount > 1); texCopy.LoadRawTextureData(tex.GetRawTextureData()); texCopy.Apply(); } }
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961