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

Replacing Sprite or Material Texture at Runtime with Binary Image Data

Discussion in 'Project Tiny' started by collinmmckinney, Mar 29, 2021.

  1. collinmmckinney

    collinmmckinney

    Joined:
    Jun 25, 2018
    Posts:
    6
    Hi there,

    I've seen some questions about loading in resources at runtime, but this question is related to what to do once the resource is loaded. I'm fetching images from the web as binary data.

    My question is: once I have this binary image data loaded into memory, how can I get it into the scene? It seems like the route is to use the binary image data to create an Image2D struct (using the Image2DMemorySource component), but I'm not sure how I can replace a Sprite's image at runtime either.

    I know this is kind of pushing the limitations of the current feature set of Tiny, but I would appreciate any guidance on this.

    Thanks!
     
  2. collinmmckinney

    collinmmckinney

    Joined:
    Jun 25, 2018
    Posts:
    6
    Here is some of what my code looks like now:
    Code (CSharp):
    1. int w = 100;
    2. int h = 100;
    3. bool srgb = true;
    4. Entity eimg = EntityManager.CreateEntity();
    5. Image2D img = new Image2D();
    6. img.imagePixelWidth = w;
    7. img.imagePixelHeight = h;
    8. img.status = ImageStatus.Loaded;
    9. img.flags = TextureFlags.UVRepeat | TextureFlags.MimapEnabled | TextureFlags.Trilinear;
    10. if (srgb)
    11.     img.flags |= TextureFlags.Srgb;
    12. EntityManager.AddComponentData(eimg, img);
    13. var buf = EntityManager.AddBuffer<Image2DMemorySource>(eimg);
    14. buf.ResizeUninitialized(w * h * 4);
    15. unsafe
    16. {
    17.     byte* readImagePtr = (byte*)msgPtr.ToPointer();
    18.     byte* dest = (byte*)buf.GetUnsafePtr();
    19.     int o = 0;
    20.     for (int y = 0; y < h; y++)
    21.     {
    22.         for (int x = 0; x < w; x++)
    23.         {
    24.             dest[o++] = readImagePtr[o];
    25.             dest[o++] = readImagePtr[o];
    26.             dest[o++] = readImagePtr[o];
    27.             dest[o++] = (byte)0xff;
    28.         }
    29.     }
    30. }
    This code successfully loads the data from msgPtr into the newly created Image2D, I just am trying to figure out what to do once that is loaded. I've tried replacing the Image2D associated with the Sprite at runtime, but that didn't seem to have any effect.