Search code examples
unity-game-engine

Is there a reason why I should use TryGetComponent instead of GetComponent


I recently found out about TryGetComponent and did some research on it. I found out that main difference is that TryGetComponent "does not allocate in the Editor when the requested component does not exist". I don't really know what that means since I am still new to Unity and why would someone request component that does not exist in the first place, so could somebody explain if I should stop using GetComponent, and if so why? Thanks in advance.


Solution

  • There might be some reasons to use GetComponent without being sure if this component exists. In this case it is necessary to check if the component is actually there or not. For example, you have an array of game objects (in this case it is RaycastHit2D array and was aquired from Physics2D.GetRayIntersectionAll method). You need to invoke a specific method from every game object that contains a specific component. You can use GetComponent and check if it equals null or not.

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

    Or you can use TryGetComponent. In this case you do not need to use GetComponent multiple times or create an additional variable. And the code looks cleaner.

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

    TryGetComponent seems to be more useful in some particular cases, but not always.