Unity:GetPixels32() 和 GetPixels32(colors) 之间的区别

Unity: Difference between GetPixels32() & GetPixels32(colors)

我正在使用 Unity 制作一个移动应用程序,我在其中打开相机并使用 WebcamTexture 从中获取数据。

我从相机得到的数据是Color32[]

我把数据存入内存,然后从内存中读取:

// Address the variable (data) to a memory location
data = new Color32[width * height];
gcHandle = GCHandle.Alloc(data, GCHandleType.Pinned);

// this didn't work
data = webcamTexture.GetPixels32();

// this worked fine
webcamTexture.GetPixels32(data);

// read data from memory using this
gcHandle.AddrOfPinnedObject() 

当我使用 webcamTexture.GetPixels32(data); 时,我能够看到相机的图像,而当我使用 data = webcamTexture.GetPixels32(); 时,我的相机出现黑屏。

我的问题:

1.这两个功能有区别吗?

2。想从Texture2D得到Color32[]怎么办? (Texture2D 有两个函数可以得到 Color32[]GetPixels32()GetRawTextureData<Color32>().ToArray(),都给我黑 屏幕)

关于标题

Difference between GetPixels32() & GetPixels32(colors)

如果您查看 API,您会发现方法签名是

public Color32[] GetPixels32(Color32[] colors = null);

所以 colors 是一个 optional parameter

所以从一个非常高层次的角度来看:没有区别,都是一样的方法。


但是,这个参数不会存在,如果有或没有它,方法的行为不会不同。

如果您继续阅读

You can optionally pass in an array of Color32s to use in colors to avoid allocating new memory each frame, which is faster when you are continuously reading data from the camera. The array needs to be initialized to a length matching width * height of the texture. If you don't pass an array, GetPixels32 will allocate one for you and return it.

您会发现传入与不传入数组的区别在于,如果您不这样做,它会在您每次调用它时分配一个新数组。如果你每一帧都使用它,这当然要贵得多。但是抛开这种性能影响,这也意味着您每次都会获得一个新的数组引用。


所以这就是说现在再次查看您正在执行的代码

data = new Color32[width * height];
gcHandle = GCHandle.Alloc(data, GCHandleType.Pinned);

所以如果你正在填充这个数组,它仍然是同一个数组 object

webcamTexture.GetPixels32(data);
var ptr = gcHandle.AddrOfPinnedObject();

所以这是可行的,因为您正在填充固定在 gcHandle.

中的相同数组引用

在另一边这不起作用

data = webcamTexture.GetPixels32();
var ptr = gcHandle.AddrOfPinnedObject();

因为您在这里创建了一个新数组引用。在这个你没有打电话

gcHandle = GCHandle.Alloc(data, GCHandleType.Pinned);

on 因此,当您到达

gcHandle.AddrOfPinnedObject()

gcHandle 仍然引用之前的 Color32[],在您调用 Alloc 时,data 引用了该 Color32[]。那仍然是一个你从未写过的空数组。


对于 Texture2D 它应该是 GetPixels32() 但您可能希望在获取指向它的指针之前先获取该数组:

var data = texture2D.GetPixels32();
var gcHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
var ptr = gcHandle.AddrOfPinnedObject();