mipLevel | 读取的 mipmap 等级。范围是 0 到纹理的 Texture.mipmapCount。默认值为 0 。 |
element | 读取的数组切片。 |
NativeArray<T> 一个原生数组,直接指向 CPU 内存中纹理的数据缓冲区。
从纹理获取原始数据。
此方法返回一个 NativeArray<T0>,该数组直接指向 CPU 上纹理的数据并具有 mipmap 等级的尺寸。该数组不包含数据的副本,因此 GetPixelData
不会分配任何内存。
例如,如果纹理是 16 × 16 像素的 RGBA32 格式,并且将 mipLevel
设置为 1
,当您使用 Color32 作为 T
(每个像素 4 个字节)时,该方法将返回一个包含 64 个元素(8 × 8 个像素)且大小为 256 字节的数组。您可以使用试验性的 GraphicsFormatUtility.ComputeMipmapSize API 来计算 mipmap 等级的尺寸。
您通常使用与纹理中的像素结构相匹配的结构用于 T
,例如,如果纹理格式使用 32 位格式的 RGBA 像素(比如 TextureFormat.RGBA32),则使用 Color32。
您可以读取返回的数组并向其写入数据以在 CPU 内存中直接获取和更改数据。如果您向数组写入数据,则必须随后调用 Apply 方法将纹理上传到 GPU。
立即使用返回的数组。如果存储数组并之后使用,如果纹理已经修改或更新,它可能无法指向正确的内存位置。
如果为 T
使用小的类型,例如 byte
,GetPixelData
可能失败,因为 NativeArray
将超出最大长度 (Int32.MaxValue
)。为避免这种情况,使用较大的类型或结构。
当 GetPixelData
失败时将引发异常。
额外资源:Apply、SetPixels、SetPixels32、GetPixelData。
using UnityEngine;
public class ExampleScript : MonoBehaviour { public void Start() { // Create a texture array var m_Texture2DArray = new Texture2DArray(16, 16, 3, TextureFormat.RGBA32, true);
// Use GetPixelData to get an array that points to mipmap level 1, in slice 1 var mip1Element1 = m_Texture2DArray.GetPixelData<Color32>(1, 1);
// Fill pixels in mipmap level 1 with white for (int i = 0; i < mip1Element1.Length; i++) { mip1Element1[i] = new Color32(255, 255, 255, 255); }
// Copy the texture changes to the GPU m_Texture2DArray.Apply(false); } }
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.