Changing shared texture at runtime without affecting project settings?

I’m trying to dynamically load a sprite atlas from the Resources directory which is used in the material of MeshRenderer on multiple objects. All of the objects with this material & texture are in a prefab.

Is there any way to change the texture of the material once and have all objects update at runtime, while at the same time not affecting my project settings?

Let’s say I have a new Texture2D object in new_tex. if I do:

gameObject.renderer.materials[0].mainTexture = new_tex;

Then an instance of the material is created for that single gameObject. I will have to have my texture updating script go through each object that needs this new texture, set the material’s mainTexture property, and create a new material instance in the process. Heck, even READING from materials[0] creates an instance (dumb dumb dumb).

Or I could do:

gameObject.renderer.sharedMaterials[0].mainTexture = new_tex; 

which switches the textures of all of the objects at once, but also saves these changes in the prefabs! Why in the world would I want to change a prefab during runtime?

Any suggestions for how to dynamically load textures while not mucking with projects settings as an unwanted side-effect?


I’m not sure if this is what you want, but if the texture is the same for all the materials that use the same shader, you can:
Remove the texture property in the property block of that shader
(But keep the uniform variable in the shader)
write a script and use Shader.setGlobalTexture(the_name_of_the_texture_varible, newtexture);

this way you won’t have to loop through all the materials and change the textures one by one.