What happens to the instantiated material after i change the .sharedMaterial?

I have an object (wall) that switch between 4 diferent materials (using .sharedMaterial) during the gameplay. But when one of them is active the player can interact with it, when this happen I use lerp to change the color over time. I do this using .material so Unity create a new instance of this material.

What will happen later when I switch again the .sharedMaterial? Will the instance auto destroy or I have to do it? And when the cycle ends and I come back to this specific material, will Unity create another instance?

It’s not just creating one new instance of the material - it’s creating a new instance of the material every frame the Lerp is occurring. When changing material properties over time, you should use the Get- and SetPropertyBlock API calls:

The instances you create by directly changing properties on a material (without using these methods) are not destroyed automatically, they are leaked. You can clean up all of them at once with Resources.UnloadUnusedAssets();

Because this is a very expensive method to call, you should use SetPropertyBlock whenever possible, which avoids leaking orphan materials in the first place.

The sharedMaterial is actually the same material in your project’s assets. You’ll see that changes to the sharedMaterial persist even after exiting playmode. It’s safe to directly change the properties of the sharedMaterial as often as you want without using the SetPropertyBlock approach.

I’m not sure how to change an instantiated material back to the sharedMaterial. You could try simply assigning the sharedMaterial to the material property?

// I don't know if this'll work, it's never actually come up for me
renderer.material = renderer.sharedMaterial;

If someone wants to chime in, that’d be great!