如果我们在项目中需要使用MonoBehaviour或ScriptableObject引用作为字典键时,会导致一些性能慢的一些问题。我们可以使用Object.GetInstanceID()改进,它返回一个整数,用于表示该对象的唯一标志值,在整个程序声明周期中,该值都不会发生变化,如果我们将其“缓存”在对象中,并将其作为字典中键,那么元素的比较将比直接使用对象引用快2至3倍。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
* Author:W
* 预设体
*/
public class PrefabObj : MonoBehaviour {
public int InstanceID;
private PrefabSystem PrefabSystem;
void Awake()
{
InstanceID = GetInstanceID();
Debug.Log("当前游戏对象的 InstanceID====="+InstanceID);
}
// Use this for initialization
void Start()
{
PrefabSystem = this.transform.parent.GetComponent<PrefabSystem>();
}
public void Init()
{
GameObjectInfo info = PrefabSystem.GetGameObjectInfo(InstanceID);
//----------
}
// Update is called once per frame
void Update () {
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameObjectInfo
{
public string Name;
public float Health;
}
public class PrefabSystem : MonoBehaviour {
public GameObject Prefab;
private Dictionary<int, GameObjectInfo> ObjDict = new Dictionary<int, GameObjectInfo>();
// Use this for initialization
void Start () {
for (int i = 0; i < 1000; i++)
{
GameObject obj = GameObject.Instantiate(Prefab) as GameObject;
obj.transform.SetParent(this.transform);
obj.transform.localPosition = Vector3.one;
obj.transform.localRotation =Quaternion.identity;
obj.transform.localScale = Vector3.one;
obj.SetActive(true);
GameObjectInfo info = new GameObjectInfo();
int id = obj.GetComponent<PrefabObj>().InstanceID;
if (!ObjDict.ContainsKey(id))
ObjDict.Add(id, info);
}
}
public GameObjectInfo GetGameObjectInfo(int ID)
{
if (ObjDict.ContainsKey(ID))
{
return ObjDict[ID];
}
return null;
}
// Update is called once per frame
void Update () {
}
}