这里有一个简单的问题..
我只是想知道是否有办法避免调用GetComponent<Script>()
里面OnTriggerEnter(Collider other)
?我试图避免这样做,因为我知道 GetComponent 很慢。
private void OnTriggerEnter(Collider other)
{
Tile tile = other.GetComponent<Tile>();
if (tile.colorIndex == GameManager.Instance.currentTargetColorIndex)
{
Debug.Log("Hit!");
}
}
最佳答案
除非此方法在单个帧中的许多对象上触发,否则可能不值得。
但是,您可以通过将 Tile 对象缓存在字典中并使用 Collider.gameObject.GetInstanceID()
对其进行索引来实现:
在某些脚本中,运行 OnTriggerEnter
的每个脚本实例都可以访问(例如游戏管理器):
public Dictionary<int, Tile> tileCache;
// ...
// Initializing:
tileCache = new Dictionary<int, Tile>();
使用示例:
private void OnTriggerEnter(Collider other)
{
int tileCacheIndex = other.gameObject.GetInstanceID();
Tile tile;
if (GameManager._instance.tileCache.ContainsKey(tileCacheIndex))
{
tile = GameManager._instance.tileCache[tileCacheIndex];
}
else
{
tile = other.GetComponent<Tile>();
GameManager._instance.tileCache[tileCacheIndex] = tile;
}
if (tile.colorIndex == GameManager.Instance.currentTargetColorIndex)
{
Debug.Log("Hit!");
}
}
因为您使用的是游戏对象的实例 ID,所以您可以执行一些操作,例如在每个图 block 的 Start 中预加载图 block 缓存。索引只是 gameObject.GetInstanceID()
,无需调用 GetComponent
。
关于c# - 如何避免在OnTriggerEnter()中调用GetComponent()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57383739/