Version: 2021.2

Texture2D.GetRawTextureData

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

返回

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

描述

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

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

The data contains the entire texture according to its width, height, data format and mipmapCount. Mipmaps are laid out in memory starting from largest, with smaller mip level data immediately following. For example, a 16x8 texture of RGBA32 format with no mipmaps will result in a 512-byte array (16x8x4), or a 128-element array if Color32 is used as a type.

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

GetRawTextureData does not allocate memory; the returned NativeArray directly points to the texture system memory data buffer. Therefore, this is the fastest way to access the pixel data.

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

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 the texture must have the read/write enabled flag set in the texture import settings. This untemplated function returns a copy of the data. If you don't need a copy or if you want to modify the data directly, use the templated version of this function. The templated function is faster because it does not make a copy.

另请注意,系统内存副本可能与当前 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