- Home /
Texture2D Generation Causing Memory Leak (System Out of Memory)
I have a C# script that will generate a texture and apply it to a mesh. If I run the generation repeatedly, Unity takes up more and more memory and eventually crashes with a System Out Of Memory error.
Here is the code I have to create the texture, and apply it to the object.
CurrentTileMapTexture = new Texture2D(textureWidth, textureHeight);
CurrentTileMapTexture.Apply();
var meshRenderer = GetComponent<MeshRenderer>();
meshRenderer.sharedMaterial.mainTexture = CurrentTileMapTexture;
I have tried clearing the memory before creating the texture with this:
Texture2D.DestroyImmediate(CurrentTileMapTexture, true);
Texture2D.DestroyImmediate(meshRenderer.sharedMaterial.mainTexture, true);
Resources.UnloadAsset(CurrentTileMapTexture);
Resources.UnloadAsset(meshRenderer.sharedMaterial.mainTexture);
CurrentTileMapTexture = null;
meshRenderer.sharedMaterial.mainTexture = null;
GC.Collect();
But this didn't prevent the memory leak. (not sure if I'm using these functions correctly though)
I've tried researching online but couldn't find a solution. Any suggestions?
Answer by andrew-lukasik · Feb 21, 2018 at 01:19 PM
UnityEngine.Object.Destroy should work for memory leaks like that. If not - that might be a engine version-specific bug.
UnityEngine.Object.Destroy( currentTexture );
currentTexture = new Texture2D( w , h );
Sidenote: I suspect that every UnityEngine.Object is referenced inside engine code somewhere hence GC.Collect alone won't release them. If that is the case then Destroy is kind of abstraction to (at least) de-reference given object from internal collections.
Correct. Every class that is derived from UnityEngine.Object has a native code counter part. All UnityEngine.Object derived classes are "tracked" on the native side and can be found again using FindObjectsOfType. If you want to get rid of any such object you have to destroy it. This also includes: GameObjects, $$anonymous$$eshes, $$anonymous$$aterials, AudioClips, .... In short any kind of object that can be serialized as asset. Note that when destroying a GameObject Unity does some additional cleanup. So all components on that gameobject are destroyed as well. When the Transform component is destroyed it will also destroy all child objects of that Transform. If a Renderer has instantiated a personal instance of a $$anonymous$$aterial that instance should also be destroyed automatically when the Renderer got destroyed. Textures however are never destroyed automatically.
What about textures/sprite in animation clip ? does it load all the sprite in memory directly or just loads sprite frame by frame.?
Your answer
Follow this Question
Related Questions
www.texture memory leak 1 Answer
SetPixels32 called with invalid number if pixels in the array 0 Answers
How to not see white background on texture 1 Answer
Unity changes pixel colors 2 Answers