Question about material dynamic assignments

Hi,

I’m dynamically attaching materials to some of my objects in C# and modify them on the fly. When Unity creates a new instance of a material, is the old material assigned to the object automatically destroyed or does it still exist in memory?
For instance if I assign material A to an object and modify it, a material A instance will be created. If I then assign a material B, will the original material A instance be destroyed or is it still kept around in memory?..

Thanks for your help :slight_smile:

Pretty sure the instance will stay in memory, that’s why it’s always recommended to not use instances when possible :stuck_out_tongue: Garbage collector I think only handles scripting garbage. If you want to remove an asset from memory I think you might need to call Resources.UnloadUnusedAssets. That will remove materials not used at the time of the call (unused in the hierarchy) However apparently this function is slow? Sometimes it’s better to leave assets loaded in if you need them later. But in your case, an instance is probably something you don’t want to keep around. Hmm… Never actually thought about the memory usage of instances. Maybe someone can correct me if I’m wrong.

Thanks for your reply - yeah, this is what I was thinking as well… wasn’t sure if the garbage collector would pick them up. I didn’t know about UnloadUnusedAssets, thanks a lot for that! I may run it when the player starts a new level to make sure things are clean, since it seems to be the best time to run it. Either before or after a level is completed so it won’t impact gameplay.
I think I’m going to bite the bullet and not rely on dynamic material assignments for that part of the code (I don’t want material instances to accumulate in memory and eventually mess up the game).
Thanks for your help :slight_smile:

I think if you load a scene it probably automatically unloads assets unless you loading additvely or you have objects that aren’t destroyed on load. Not sure about that again though xD

You can still have dynamic materials! If you make a couple of preset materials and just reference them you can still swap between them without creating instances. That’s what I’m doing for crowd simulation. (Instead of randomly generating clothing color, it just chooses from preset materials) and glad to help! :slight_smile: