using System.Collections; using System.Collections.Generic; using UnityEngine; namespace game { public class ScratchCardUtils { public static void UpdateTexture2D(Texture2D texture2D, RenderTexture renderTexture, int width, int height) { RenderTexture tmp = RenderTexture.active; RenderTexture.active = renderTexture; texture2D.ReadPixels(new Rect(0, 0, width, height), 0, 0); RenderTexture.active = tmp; texture2D.Apply(); } public static Texture2D GetReadableCopy(RenderTexture renderTexture, TextureFormat format = TextureFormat.ARGB32, bool mipMaps = false, int width = 0, int height = 0) { var newTexture = default(Texture2D); if (renderTexture != null) { if (width <= 0) { width = renderTexture.width; } if (height <= 0) { height = renderTexture.height; } if (CanReadPixels(format) == true) { newTexture = new Texture2D(width, height, format, mipMaps, false); var tmp = RenderTexture.active; RenderTexture.active = renderTexture; newTexture.ReadPixels(new Rect(0, 0, width, height), 0, 0); RenderTexture.active = tmp; newTexture.Apply(); } } return newTexture; } public static RenderTexture ReleaseRenderTexture(RenderTexture renderTexture) { return ReleaseTemporary(renderTexture); } public static RenderTexture ReleaseTemporary(RenderTexture renderTexture) { if (renderTexture != null) { renderTexture.DiscardContents(); RenderTexture.ReleaseTemporary(renderTexture); } return null; } public static bool CanReadPixels(TextureFormat format) { if (format == TextureFormat.RGBA32 || format == TextureFormat.ARGB32 || format == TextureFormat.RGB24 || format == TextureFormat.RGBAFloat || format == TextureFormat.RGBAHalf) { return true; } return false; } public static RenderTexture GetRenderTexture(RenderTextureDescriptor desc, bool sRGB) { desc.sRGB = sRGB; return GetTemporary(desc, "ScratchCardUtils GetRenderTexture"); } public static RenderTexture GetTemporary(RenderTextureDescriptor desc, string title) { var renderTexture = RenderTexture.GetTemporary(desc); // TODO: For some reason RenderTexture.GetTemporary ignores the useMipMap flag?! if (renderTexture.useMipMap != desc.useMipMap) { renderTexture.Release(); renderTexture.descriptor = desc; renderTexture.Create(); } return renderTexture; } } }