Unity 优化相关 - daaoling/daaoling.github.io GitHub Wiki
Unity 优化相关
Does Unity Cache Results of Resources.Load?
mTest.cs
public class mTest : MonoBehaviour
{
void OnGUI()
{
if (GUI.Button(new Rect(10, 10, 150, 100), "I am a button")) Test();
}
void Test()
{
// call each one once, to make sure any internal cache is able to be populated
Resources.Load<Texture2D>("Soils/Grass");
float time = Time.realtimeSinceStartup;
for (int i = 0; i < 10000; i++)
Resources.Load<Texture2D>("Soils/Grass");
Debug.Log("NoCache) " + (Time.realtimeSinceStartup - time)); ///NoCache) 0.02871513
VResources.Load<Texture2D>("Soils/Grass");
float time2 = Time.realtimeSinceStartup;
for (int i = 0; i < 10000; i++)
VResources.Load<Texture2D>("Soils/Grass");
Debug.Log("Cache) " + (Time.realtimeSinceStartup - time2)); ///Cache) 0.003810763
}
}
VResources.cs
public static class VResources
{
static Dictionary<string, Object> resourceCache = new Dictionary<string, Object>();
public static T Load<T>(string path) where T : Object
{
if (!resourceCache.ContainsKey(path))
resourceCache[path] = Resources.Load<T>(path);
return (T)resourceCache[path];
}
}