我是否有理由使用 TryGetComponent 而不是 GetComponent

Mar*_*rko 6 unity-game-engine

我最近发现了TryGetComponent并对其进行了一些研究。我发现主要区别在于TryGetComponent “当请求的组件不存在时不会在编辑器中分配”。我真的不知道这意味着什么,因为我对 Unity 还很陌生,为什么有人会请求一开始就不存在的组件,所以有人可以解释一下我是否应该停止使用GetComponent,如果是的话为什么?提前致谢。

小智 9

可能有一些原因需要在不确定该组件是否存在的情况下使用GetComponent 。在这种情况下,有必要检查该组件是否确实存在。例如,您有一个游戏对象数组(在本例中是 RaycastHit2D 数组,是从Physics2D.GetRayIntersectionAll 方法获取的)。您需要从包含特定组件的每个游戏对象调用特定方法。您可以使用GetComponent并检查它是否等于 null。

RaycastHit2D[] ray = Physics2D.GetRayIntersectionAll(_mainCamera.ScreenPointToRay(Input.mousePosition));
        foreach (RaycastHit2D item in ray)
        {
            var myClass = item.transform.GetComponent<MyClass>();
            if (myClass != null )
            {
                myClass.MyMethod();
            }
        }
Run Code Online (Sandbox Code Playgroud)

或者您可以使用TryGetComponent。在这种情况下,您不需要多次使用 GetComponent 或创建额外的变量。而且代码看起来更干净。

RaycastHit2D[] ray = Physics2D.GetRayIntersectionAll(_mainCamera.ScreenPointToRay(Input.mousePosition));
        foreach (RaycastHit2D item in ray)
        {
            
            if (item.transform.TryGetComponent(out MyClass myClass))
            {
                myClass.MyMethod();
            }
        }
Run Code Online (Sandbox Code Playgroud)

TryGetComponent在某些特定情况下似乎更有用,但并非总是如此。