I have a byte[]
of colors that I need to transfer to Texture2D
object via SetPixels(Color32[])
.
I want to know what the fastest way to create the Color32[]
from the byte[]
is.
Since each Color32
is 4 bytes (1 byte per channel), there would be one quarter the number of elements.
Array.CopyTo
doesn't allow different object array types.
From what I read, it seems like managed code can't reinterpret the byte[]
as Color32[]
and skip the copy altogether.
The reverse of this (Color32[]
-> byte[]
) has a SO solution via marshalling, but there seems to be a ton of copying involved.
private static byte[] Color32ArrayToByteArray(Color32[] colors)
{
int length = 4 * colors.Length;
byte[] bytes = new byte[length];
IntPtr ptr = Marshal.AllocHGlobal(length); // unmanaged memory alloc
Marshal.StructureToPtr(colors, ptr, true); // memcpy 1
Marshal.Copy(ptr, bytes, 0, length); // memcpy 2
Marshal.FreeHGlobal(ptr);
return bytes;
}
For my case, I'm using:
int length = bytes.Length;
IntPtr ptr = Marshal.AllocHGlobal(length); // unmanaged mem alloc
Marshal.Copy(bytes, 0, ptr, length); // memcpy 1
Marshal.PtrToStructure(ptr, colors); // memcpy 2
Marshal.FreeHGlobal(ptr);
However, I don't see the texture updating after doing myTexture.SetPixels(colors)
. Still trying to figure out why.
Regardless, do I have to do 2 mem copies to accomplish this in C#? Seems like such a waste.. I was looking at unions in C# to get around the copies.