To avoid loading resources repeatedly, once a resource is loaded, it is cached in the ResourceManager. The cache itself occupies memory and video memory, so when developers no longer need the cached content, they need to manually release the cached content.
Note: Resources are interdependent.
For example, the entity shown in the figure below contains a MeshRenderer component, which depends on Material. Material may be referenced by multiple MeshRenderers. If Material is released, other MeshRenderers that reference it will not be able to find the Material and will report an error.
Note: JavaScript cannot track object references. Generally, in weakly typed languages like JavaScript, memory management functions are not provided to developers. All object memory is managed through garbage collection mechanisms, and you cannot determine when an object will be released, so there is no destructor to call for releasing referenced resources.
ResourceManager
provides a set of resource releases based on reference counting, which requires developers to manually call gc:
engine.resourceManager.gc();
If you need to verify whether assets have been successfully released, you can follow the steps below and open the following example on a blank page:
In this example, Texture2D
and Sprite
are created to render 2D sprites during initialization. When you click the GC button in the upper right corner, the root
node is destroyed, and the reference counts of the texture and sprite assets are cleared. At this point, these assets will be truly destroyed. Taking memory snapshots before and after gc
can give a more intuitive understanding of this process.