How to get a readable sprite from a unreadable sprite that is packed into an sprite atlas in player builds
What i need is a function that i provide a Sprite that is unreadable and packed into an sprite atlas, and the function needs to give me a copy of that sprite that is readable, my initial solution (bellow) was working but them while building the game i realized that it used the namespace UnityEditor.Sprites (the SpriteUtility.GetSpriteTexture() method) which is not available at player builds.
public static Sprite GetReadableDuplicate(this Sprite originalSprite)
{
Texture2D texture2D = SpriteUtility.GetSpriteTexture(originalSprite, false);
Texture2D duplicateTexture = DuplicateTexture(texture2D);
Sprite newSprite = Sprite.Create(duplicateTexture, new Rect(0, 0, duplicateTexture.width, duplicateTexture.height),
Vector2.zero, pixelsPerUnit: 100, uint.MaxValue, SpriteMeshType.FullRect);
return newSprite;
}
private static Texture2D DuplicateTexture(Texture2D source)
{
RenderTexture renderTex = RenderTexture.GetTemporary(
source.width,
source.height,
0,
RenderTextureFormat.Default,
RenderTextureReadWrite.Linear);
Graphics.Blit(source, renderTex);
RenderTexture previous = RenderTexture.active;
RenderTexture.active = renderTex;
Texture2D readableText = new Texture2D(source.width, source.height);
readableText.ReadPixels(new Rect(0, 0, renderTex.width, renderTex.height), 0, 0);
readableText.Apply();
RenderTexture.active = previous;
RenderTexture.ReleaseTemporary(renderTex);
return readableText;
}
The reason i need this is because in my game i have a toon of sprites which are used for buttons/toggles and i need to set the alphaminimumhitthreshold on the image components of those, i can't afford to set all of these sprites as Read/Write enabled in the texture import settings so the ideal solution would be to figure a way of making this work inside player builds.