c# - 如何避免在OnTriggerEnter()中调用GetComponent()?

标签 c# unity-game-engine

这里有一个简单的问题..

我只是想知道是否有办法避免调用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/

相关文章:

c# - Unity 中初始跳转后 "isGrounded"变量不会更改为 false

c# - Unity 2D 本地面不平坦时,为什么我的角色不会跳跃?

c# - 为什么单击文本框会导致 AutoScroll 面板滚动回顶部?

c# - 在椭圆中间绘制文本

c# - 如何从其他表单访问列表

facebook - Firebase 实时数据库下载使用率高

c# - 在我的 C# 应用程序中延迟加载

c# - 在不阻塞 UI 的情况下在 ViewModel 中加载大量数据

c# - 变量设置行会干扰顶级语句

c# - Unity 2D 碰撞检测