I have been developing Unity for a while, and I have also learned a few tricks of memory and Performance optimization. Although it is not a system, in order to prevent forgetting, it is also a simple summary.
Resource Cache
In some cases, such as a dress-up scene, the general practice is that we load the model of the clothing, extract the SkinnedMeshRender from it, merge multiple SMRs, and then bind them to the characters through bones, and finally destroy the clothing.
If we only have one character, there is no problem, but if we have n nude characters, even wearing the same set of costumes, we need to initialize all the costumes n times and destroy them n times, which is not good for CPU and memory.
At this time, we can use the cache method, since each time we only need to extract the SMR of the model, then all our characters are extracted from the same model
1 2 3 4 5 6 7 8 9 10 11 12 13 14
using System.Threading.Tasks; using UnityEngine;
namespaceResourceManager { publicinterfaceIResourceCache { public Task<GameObject> GetResource(string location); publicvoidReleaseResource(string location);
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Character; using UnityEngine;
The resource caching method above is suitable for the case where all objects share the same set of resources, but in some cases, we may need exclusive resources. For example, n game characters need to be controlled by n different players, so we need n instances.
In this case, how can we optimize it?
We assume such a situation, if the room will continue to have players in and out, every time a player comes in, the game process needs to load an object, the player exits, the object needs to be destroyed, if the frequency is too high, in fact, the CPU is also a burden.
At this time, we can use the resource pool method. After instantiation, if the player quits the game, we do not destroy the object, but return it to the resource pool. After another player connects, we directly take one from the pool and give it to the player. Just control it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
using System.Threading.Tasks; using UnityEngine;
namespaceResourceManager { publicinterfaceIResourcePool { public Task<GameObject> GetResource(string location); public GameObject GetResourceWithoutCreate(string key);
publicvoidClear() { foreach (var item in _pool) { foreach (var obj in item.Value) { Release(obj); } } } } }
Materials to reuse as much as possible
If conditions permit, such as the material of all objects is the same, and can change at the same time, do not create a new material for each object.
Merge Texture
After merging Texture, if you don’t need to modify it later, try to call the Apply method on the new Texture to release the memory used for modification.