Search Unity

Help Wanted GetPixels returns distorted sprite on compressed texture

Discussion in '2D' started by ryanas, May 26, 2021.

  1. ryanas

    ryanas

    Joined:
    Oct 2, 2013
    Posts:
    14
    I am currently cutting sprites from a texture and saving them as separate textures, which works sometimes but causes distortion copying pixels on a texture which has been compressed.

    This is how I am cutting the sprites:

    Code (CSharp):
    1. var croppedTexture = new Texture2D((int) sprite.rect.width, (int) sprite.rect.height);
    2.  
    3. var pixels = sprite.texture.GetPixels((int) sprite.textureRect.x,
    4.                 (int) sprite.textureRect.y,
    5.                 (int) sprite.textureRect.width,
    6.                 (int) sprite.textureRect.height);
    7.  
    8. croppedTexture.SetPixels(pixels);
    9. croppedTexture.Apply();
    10. croppedTexture.name = sprite.name;


    This is what the image should look like
    upload_2021-5-26_18-1-21.png

    but it ends up looking like this
    upload_2021-5-26_18-1-45.png
     

    Attached Files:

  2. ryanas

    ryanas

    Joined:
    Oct 2, 2013
    Posts:
    14
    Figured I'll answer this in case anyone makes the same mistake as me:

    I was writing
    Code (CSharp):
    1. var croppedTexture = new Texture2D((int) sprite.rect.width, (int) sprite.rect.height);
    whereas thats getting the wrong rect info and I should've used sprite.textureRect.width and sprite.textureRect.height instead.
     
unityunity