C# 如何避免在OnTiggerEnter()中调用GetComponent()?

C# 如何避免在OnTiggerEnter()中调用GetComponent()?,c#,unity3d,C#,Unity3d,这里有一个简单的问题 我只是想知道是否有一种方法可以避免在OnTriggerEnter(Collider-other)内部调用GetComponent()?我尽量避免这样做,因为我知道GetComponent很慢 private void OnTriggerEnter(Collider other) { Tile tile = other.GetComponent<Tile>(); if (tile.colorIndex == GameManager.Instance

这里有一个简单的问题

我只是想知道是否有一种方法可以避免在
OnTriggerEnter(Collider-other)
内部调用
GetComponent()
?我尽量避免这样做,因为我知道GetComponent很慢

private void OnTriggerEnter(Collider other)
{
    Tile tile = other.GetComponent<Tile>();
    if (tile.colorIndex == GameManager.Instance.currentTargetColorIndex)
    {
        Debug.Log("Hit!");
    }
}
专用无效对撞机(对撞机其他)
{
Tile Tile=other.GetComponent();
if(tile.colorIndex==GameManager.Instance.currentTargetColorIndex)
{
Log(“Hit!”);
}
}

除非此方法在单个帧中对多个对象触发,否则它可能不值得

但是,您可以通过在字典中缓存平铺对象并使用
Collider.gameObject.GetInstanceID()
为它们编制索引来实现这一点:


在某些脚本中,运行
OnTriggerEnter
的脚本的每个实例都可以访问(例如游戏管理器):

公共字典tileCache;
// ...
//初始化:
tileCache=新字典();
示例用法:

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!");
    }
}
专用无效对撞机(对撞机其他)
{
int tileCacheIndex=other.gameObject.GetInstanceID();
瓷砖;
if(游戏管理器._instance.tileCache.ContainsKey(tileCacheIndex))
{
tile=GameManager.\u instance.tileCache[tileCacheIndex];
}
其他的
{
tile=other.GetComponent();
GameManager.\u instance.tileCache[tileCacheIndex]=平铺;
}
if(tile.colorIndex==GameManager.Instance.currentTargetColorIndex)
{
Log(“Hit!”);
}
}

因为您使用的是游戏对象的实例ID,所以可以在每个磁贴的开始处预加载磁贴缓存。索引应该是
gameObject.GetInstanceID()
,不需要调用
GetComponent

您也可以使用碰撞器作为键。这正是我要找的!非常感谢您,值得检查GetInstanceID是否确实比GetComponent快。好的一点是,如果GetInstanceID没有明显比Get Component快,那么最好使用
other.gameObject
作为索引,并让字典使用
gameObject
键。正如Iggy所提到的,您可以使用collider作为键,不需要获取InstanceID,但是冲突本身的成本非常高,我认为collison上的GetComponent并没有那么糟糕
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!");
    }
}