Why does setPixel persist after exit ??


I wrote this code to change a part of texture with another texture

        // the texture that i will paint with 
		public Texture2D targetTexture ;
		//temporary texture
		public Texture2D tmpTexture, tmpMainTexture;

		void Start ()
				//setting temp texture width and height 
				tmpMainTexture = (Texture2D)renderer.material.mainTexture;
				tmpTexture = (Texture2D)renderer.material.mainTexture;
				for (int y =30; y<tmpTexture.height; y++) {
						for (int x = 30; x<tmpTexture.width; x++) {
								//filling the temporary texture with the target texture
								tmpTexture.SetPixel (x, y, targetTexture.GetPixel (x, y));
				tmpTexture.Apply ();
				//change the object main texture 
				renderer.material.mainTexture = tmpTexture;

what i don’t understand is that why the texture itself (in the project hierarchy)also get changed ? i checked out the PNG file and it is intact, also when i restart the project or change the texture type (from Advanced to Texture for example), the texture get back to it’s original state, any help please ?

You should operate on an instance of the texture, rather than the actual texture in the project.

I had the same question just yesterday, take a look here:


I supplied some code there, I don’t know if it is the most elegant solution, but I created a new texture with the same height and width and just took all the pixels from the previous texture via setPixels32().