Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice

Texture2D could accept a SetPixels with NativeArray<Color>?

Discussion in '2018.2 Beta' started by Fattard, Apr 21, 2018.

  1. Fattard

    Fattard

    Joined:
    Oct 20, 2015
    Posts:
    2
    Hello, I would like to know if would be convenient for Texture2D method of SetPixels to also allows receiving a NativeArray<Color> as argument.

    I'm doing some native work that creates a mini "render buffer" to be applied to a Texture2D, but I need to copy the content back to a normal Color[] before calling SetPixels.
    By allowing NativeArray<Color> as argument, we could work with native pixel processing and avoid a unnecessary array copy every frame.

    Current code:
    Code (CSharp):
    1. s_displayPixels = tex.GetPixels();
    2. m_displayPixelsNative = new NativeArray<Color>(s_displayPixels.Length, Unity.Collections.Allocator.Persistent);
    3. // < .... >
    4. unsafe
    5. {
    6.     void* ptr = m_displayPixelsNative.GetUnsafePtr();
    7.     for (int i = 0; i < s_displayPixels.Length; i++)
    8.     {
    9.         s_displayPixels[i] = *(Color*)((byte*)ptr + i * sizeof(Color));
    10.     }
    11. }
    12.  
    13. tex.SetPixels(s_displayPixels);
    14. tex.Apply();
    Thank you
     
  2. LennartJohansen

    LennartJohansen

    Joined:
    Dec 1, 2014
    Posts:
    2,394
    Hi. I did not test it yet, but 2018.2 Beta is supposed to have NativeArray access to texture data.
    It would allow you to directly modify the data buffer without the need of copying.

    This is from the release notes.

    "Added Texture2D.GetRawTextureData overload that returns a direct NativeArray into texture's pixel data. This allows runtime pixel data modification without an extra memory copy of SetPixels32 or LoadRawTextureData. (1015723)"

    Lennart
     
  3. Fattard

    Fattard

    Joined:
    Oct 20, 2015
    Posts:
    2
    Thank you for letting me know. It works great for my needs (after changing the color format from floats to bytes).
     
  4. LennartJohansen

    LennartJohansen

    Joined:
    Dec 1, 2014
    Posts:
    2,394
    Yes. And you can do the conversion in a job. Offloading everything from the main thread.