Garbage collector overview
Managed memory introductionUnityâs managed memory system is part of the C# scripting environment provided by either the Mono or IL2CPP Virtual Machines (VM). The benefit of the managed memory system is that it manages the release of memory, so you donât need to manually request the release of memory through your code. These VM offer a controlled memory environment consisting of the following parts:
Unityâs managed memory system uses a garbage collector and a managed heap to automatically free memory allocations when your scriptsA piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary no longer hold any references to those allocations. This helps protect against memory leaks, which happen when allocated memory is never freed because the reference required to free it manually has been lost.
Unityâs memory management system guards memory access, which means that you canât access memory that has been freed, or that was never valid for your code to access. However, this memory management process impacts runtime performance, because allocating managed memory is time-consuming for the CPU. Garbage collection might also stop the CPU from doing other work until it completes.
In the following diagram, the blue box represents a quantity of memory that Unity allocates to the managed heap. The white boxes within it represent data values that Unity stores within the managed heapâs memory space. When additional data values are needed, Unity allocates them the free space from the managed heap (annotated A).
A quantity of memory. Marked A on the diagram is some free memory. Types allocated to the heapWhen a method is called, the scripting back end copies the values of its parameters to an area of memory reserved for that specific call, in a data structure called a call stack. The scripting back end can quickly copy data types that occupy a few bytes. However, itâs common for objects, strings, and arrays to be much larger, and itâs inefficient for the scripting back end to copy these types of data on a regular basis.
All non-null reference-type objects and all boxed value-typed objects in managed code must be allocated on the managed heap.
Itâs important that youâre familiar with value and reference types, so that you can effectively manage your code. For more information, refer to Microsoftâs documentation on value types, and reference types.
Memory fragmentation and heap expansionWhen Unity releases an object, the memory that the object occupied is freed up. However, the free space doesnât become part of a single large pool of free memory.
The objects on either side of the released object might still be in use. Because of this, the freed space is a gap between other segments of memory. Unity can only use this gap to store data of identical or lesser size than the released object. This situation is called memory fragmentation, and the following diagram shows an example of this:
A quantity of memory, with some objects released represented by grey dashed lines.Memory fragmentation happens when thereâs a large amount of memory available in the heap, but itâs only available in the memory gaps between objects. Even though thereâs enough total space for a large memory allocation, the managed heap canât find a large enough single block of contiguous memory to assign to the allocation.
If a large object is allocated and thereâs insufficient contiguous free space to accommodate it, the Unity memory manager performs two operations:
Unity doesnât release the memory allocated to the managed heap when it expands regularly. Instead, it retains the expanded heap, even if a large section of the heap is empty. This prevents the need to re-expand the heap if further large allocations occur.
On most platforms, Unity eventually releases the memory that the empty portions of the managed heap uses back to the operating system. The interval at which this happens isnât guaranteed and is unreliable. This requires these portions to consist of one or more full memory pages (4 KB on most platforms).
Managed heap and native memoryThe garbage collector doesnât clear out native memory objects or other native allocations. Unity only clears native memory in the following situations:
Resources.UnloadUnusedAssets
is called. You can manually call UnloadUnusedAssets
, or Unity calls it automatically when unloading a sceneA Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More infoLoadSceneMode.Single
. For asynchronous scene unloads you can request assets that were dynamically created and embedded in the scene at build-time with the parameters of SceneManager.UnloadSceneAsync
and the option UnloadSceneOptions.UnloadAllEmbeddedSceneObjects
. Calling SceneManager.UnloadSceneAsync
with UnloadSceneOptions.UnloadAllEmbeddedSceneObjects
doesnât unload regular assets that Unity loaded to use in the scene, or dynamically and run-time created assets.Destroy
is called on an object.Resources.UnloadUnusedAssets
unloads all native objects that no longer have any references pointing to them. If you want to free the memory earlier, for example if you have full screen RenderTexture
instances on platforms with low RAM, call Destroy
on the objects.
If you want to have more control over the assets that stay in memory, use AssetBundles and Addressables.
Important: Calling UnloadUnusedAssets
or GC.Collect
is a CPU-intensive process. In large projects it might take several seconds to complete
Before calling UnloadUnusedAssets
, make sure youâre not holding managed references to the native objects you want to be cleaned up, or the native objects wonât be unloaded. Static fields and events are common ways to hold on to these objects without meaning to. For more information on how to analyze these issues with the Memory Profiler, refer to Managed shell objects in the Memory Profiler package documentation.
Resources.UnloadUnusedAssets
API referenceGarbage collector overview
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4