Skip to content

Instantly share code, notes, and snippets.

@develax
Created May 25, 2019 10:07
Show Gist options
  • Save develax/87ca8dd52f10c9ff608d8f4ab511d81a to your computer and use it in GitHub Desktop.
Save develax/87ca8dd52f10c9ff608d8f4ab511d81a to your computer and use it in GitHub Desktop.

Unity 3D: how to create Texture2D from Sprite2D

private Texture2D GetSpriteTexture(Sprite sprite)
{
    int x = Mathf.FloorToInt(sprite.rect.x);
    int y = Mathf.FloorToInt(sprite.rect.y);
    int w = Mathf.FloorToInt(sprite.rect.width);
    int h = Mathf.FloorToInt(sprite.rect.height);
    Color[] pixels = sprite.texture.GetPixels(x, y, w, h);
    var texture = new Texture2D(w, h, TextureFormat.ARGB32, false);
    texture.SetPixels(pixels);
    texture.Apply();
    return texture;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment