Texture2D SetPixels/Apply changes not permanent.

I am trying to modify a Texture2D and the changes are not being saved. Here is my problem:

Texture2D texture = spriteRenderer.sprite.texture;

Now the changes are visible in the screen. If I go to another scene where the texture is not visible, it returns to the original (like re-imported). It happens everywhere (editor, mobile) and I don’t want it. Also happens if I restart the game.

According to the docs: “Texture2D assets are never automatically instantiated when modifying them in iOS and Android projects. Any modifications made to these assets through scripting are always permanent, and never undoable. So if you change the pixels of a texture file, the change is permanent.” (Unity - Manual: Modifying Source Assets Through Scripting)

Does anyone knows why my assets are not being modified as the documentation clearly states? am I missing something?


I encountered a similar problem - I was able to bypass the issue by the following:

System.IO.File.WriteAllBytes( path, tex.EncodeToPNG() )

If you are working in an editor script you can automatically determine the path of the script with this:

string path = Application.dataPath + "/../" + AssetDatabase.GetAssetPath( tex );

This won’t work on some build targets, such as the web player, but hopefully will suffice as a workaround.

As avianling hinted, this is not possible to to at all outside the inspector.

This a possible workaround:

protected void SaveTexture(Texture2D texture)
        path = Application.persistentDataPath + "/" + texture.name;
		File.WriteAllBytes(path, texture.EncodeToPNG());

protected Texture2D RetriveTexture(Texture2D texture)
		Texture2D newTexture = new Texture2D(texture.width, texture.height);

		if (File.Exists(path)){
		} else {
			newTexture = texture;

		return newTexture;

Then you can set this two functions OnDisable and in OnEnable to automatically do it. In the editor you can still get some weird behaviors. But on play mode it would be like if you effectively override the original texture (which is sadly impossible).

Also note that you need to know the width and height of the texture before loading, as you cannot easily retreive that information from the file.

You can mark this as answered :slight_smile: