- Home /
Create / Modify Texture2D to Read/Write Enabled at Runtime
How can I create or edit a texture, at runtime, with its read/write property enabled? The TextureFormat doesn't seem to help, and I can't find out how to make it work.
Note: TextureImporter and AssetDatabase don't work. They require the UnityEditor namespace, and that doesn't work in an exported build (I'm making this for iOS).
In the editor, you can just set a texture's type to Advanced and set its Read/Write Enabled property to true, but of course I don't have access to the editor at runtime.
Thanks!
Answer by kamyflex · Mar 17, 2020 at 03:57 AM
From here : https://stackoverflow.com/questions/44733841/how-to-make-texture2d-readable-via-script @nyonge , i got this, and it worked well for me :
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;
}
My texture is blank when I use this method. Do you how to fix that?
Answer by Bunny83 · Feb 21, 2017 at 08:57 PM
"Readonly" only applies to assets that you import at edittime. So if you imported a texture at edittime and you didn't make it readable, you can't read it at runtime and you can't make it readable. So if you need textures which you imported in the editor readable at runtime you have to mark it as readable inside the editor.
Textures created at runtime are always readable unless you pass "true" as second parameter to Apply in which case you made the texture none-readable forever just like an asset that never was.
If you load images at runtime from external sources they also are readable by default
Answer by MikeHergaarden · Feb 21, 2017 at 08:17 PM
If you want to make something readable, you'd best create a new readable texture at runtime.
If you want to make a read/write texture "static", use: https://docs.unity3d.com/ScriptReference/Texture2D.Apply.html