Texture2D.LoadRawTextureData

切换到手册
public void LoadRawTextureData (byte[] data);
public void LoadRawTextureData (NativeArray<T> data);
public void LoadRawTextureData (IntPtr data, int size);

参数

data用于初始化纹理像素的原始数据数组。
size数据大小(以字节为单位)。

描述

使用原始预格式化数据填充纹理像素。

该函数使用原始数据填充纹理像素内存。对于将压缩纹理格式数据加载到纹理中的情况,该函数非常有用。

传递的数据应具有所需的大小,以便根据其宽度、高度、数据 formatmipmapCount 填充整个纹理;否则会抛出 UnityException。Mipmap 的内存布局是从最大级别开始,较小 Mip 级别的数据紧随其后。例如,对于没有 Mipmap 的 RGBA32 格式的 16x8 纹理,可以使用 512 字节数组 (16x8x4) 进行填充。

对于运行时纹理生成,还可以通过返回 Unity.Collections.NativeArrayGetRawTextureData 直接写入纹理数据。这可以提高速度,因为避免了 LoadRawTextureData 所执行的内存复制。

设置图像数据后,调用 Apply 会将其实际上传到 GPU。

另请参阅:SetPixelsSetPixels32LoadImageApplyGetRawTextureData

using UnityEngine;

public class ExampleScript : MonoBehaviour { public void Start() { // Create a 16x16 texture with PVRTC RGBA4 format // and fill it with raw PVRTC bytes. Texture2D tex = new Texture2D(16, 16, TextureFormat.PVRTC_RGBA4, false); // Raw PVRTC4 data for a 16x16 texture. This format is four bits // per pixel, so data should be 16*16/2=128 bytes in size. // Texture that is encoded here is mostly green with some angular // blue and red lines. byte[] pvrtcBytes = new byte[] { 0x30, 0x32, 0x32, 0x32, 0xe7, 0x30, 0xaa, 0x7f, 0x32, 0x32, 0x32, 0x32, 0xf9, 0x40, 0xbc, 0x7f, 0x03, 0x03, 0x03, 0x03, 0xf6, 0x30, 0x02, 0x05, 0x03, 0x03, 0x03, 0x03, 0xf4, 0x30, 0x03, 0x06, 0x32, 0x32, 0x32, 0x32, 0xf7, 0x40, 0xaa, 0x7f, 0x32, 0xf2, 0x02, 0xa8, 0xe7, 0x30, 0xff, 0xff, 0x03, 0x03, 0x03, 0xff, 0xe6, 0x40, 0x00, 0x0f, 0x00, 0xff, 0x00, 0xaa, 0xe9, 0x40, 0x9f, 0xff, 0x5b, 0x03, 0x03, 0x03, 0xca, 0x6a, 0x0f, 0x30, 0x03, 0x03, 0x03, 0xff, 0xca, 0x68, 0x0f, 0x30, 0xaa, 0x94, 0x90, 0x40, 0xba, 0x5b, 0xaf, 0x68, 0x40, 0x00, 0x00, 0xff, 0xca, 0x58, 0x0f, 0x20, 0x00, 0x00, 0x00, 0xff, 0xe6, 0x40, 0x01, 0x2c, 0x00, 0xff, 0x00, 0xaa, 0xdb, 0x41, 0xff, 0xff, 0x00, 0x00, 0x00, 0xff, 0xe8, 0x40, 0x01, 0x1c, 0x00, 0xff, 0x00, 0xaa, 0xbb, 0x40, 0xff, 0xff, }; // Load data into the texture and upload it to the GPU. tex.LoadRawTextureData(pvrtcBytes); tex.Apply(); // Assign texture to renderer's material. GetComponent<Renderer>().material.mainTexture = tex; } }