Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more..
    Dismiss Notice
  3. Dismiss Notice

Sprite Copy

Discussion in '2D' started by scossgrove, Jun 25, 2021.

  1. scossgrove

    scossgrove

    Joined:
    Jan 6, 2016
    Posts:
    23
    Hi,

    I have a texture2d set at 128 x 128. I have a sprite that has a texture that is 512 x 512 and rect (128, 256,128,128).

    Every time I do a set pixel from the sprite.texture the image is shifted and i don't get what I think i should.

    My question is how to i copy the 128x 128 pixels from the sprite onto the texture2d?

    The following is the merge method I am using. Can anyone help?

    Code (CSharp):
    1.  Texture2D MergeTextures(Texture2D texture_1, Texture2D texture_2, Rect texture2_Rect)
    2.         {
    3.             Texture2D merge_result = new Texture2D(texture_1.width, texture_1.height);
    4.  
    5.             for (int i = 0; i < merge_result.width; i++)
    6.             {
    7.                 for (int j = 0; j < merge_result.height; j++)
    8.                 {
    9.  
    10.                     Color tex1_color = texture_1.GetPixel(i, j);
    11.                     Color tex2_color = texture_2.GetPixel(i + (int)texture2_Rect.x, j + (int)texture2_Rect.y);
    12.                     Color merged_color = tex2_color.a == 0 ? tex1_color : tex2_color;
    13.                     merge_result.SetPixel(i, j, merged_color);
    14.                 }
    15.             }
    16.  
    17.             merge_result.Apply();
    18.             return merge_result;
    19.  
    20.         }
     
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
    Hi @scossgrove

    Did you already solve your issue?

    Anyway, IIRC texture coordinates start from bottom left corner, not upper left corner so did you take this into account?

    Also, make sure your condition works - actually I would first remove that ternary operator, and sample the source texture without it to see that texture reading works otherwise.

    Also, source texture has to be read/write enabled, so you can read it. But I guess you don't have problem with this, since this will throw an exception into your console.

    Otherwise I think your code should work.
     
    Last edited: Jun 26, 2021
  3. scossgrove

    scossgrove

    Joined:
    Jan 6, 2016
    Posts:
    23
    Thanks, I'm sure i was using the wrong rect from the sprite. I am using the rect not TextureRect now and it is working.
     
    eses likes this.