Lag when settings MeshRenderer.sharedMaterial

Hi, I posted recently about having a problem with asset bundle loading(the game would stall for a split second when loading). I thought this would happen because of the asset bundle size, but I tried it today with a 50MB asset bundle, and game loads the bundle successfully with no stalls or FPS drops at all.

However, when I try to assign the loaded material(asset bundle contains a material with a 50MB texture) to a mesh renderer, I get an about 500ms freeze.

I tracked the memory usage, and by the time the freeze happens the texture is already loaded in system memory.

So why does that happen? Does Unity make a copy of the material(and texture) when assigning it, in video memory, and that causes the 500ms freeze? Or why else?

And more importantly, how to avoid it?

The delay could well be the result of using the sharedMaterial property. Unless you want to modify a source asset, you should probably just use the material property instead (see here for an explanation of sharedMaterial).

I have tried using both .material or .shaderMaterial. The same thing happens.

There is no source material really, the material is loaded straight from the bundle and I add MeshRenderer using AddComponent just before loading the material so there is no source material, per se.

Just some additional info:

This will also happens if doing “MeshRenderer.sharedMaterial = (Material)Resources.Load(“BigMaterial”);”. So asset bundles specifically have nothing to do with the problem.

It happens when I load something dynamically. Once loaded once, further calls on Resource.Load() don’t cause a delay. (For example in the editor I press Play, load the resource, get a short delay when setting the material, now I stop the game and run it again, load the resource again, and this time no delay(because it stayed in the memory)). (This is specific to Resource.Load, since AssetBundle-s don’t stay in the memory after stopping the game in the Editor; for them there is a delay each time I start the game)

Alright I hope I figured this out:

This /seems/ to only happen in the editor when Hierarchy screen is open.

So I guess, problem solved.

nice info, thank you