Consider using layer masks instead of relying on GetComponent

I read somewhere that calling GetComponent too often can result in performance issues, so I decided to roughly compare the render stats using the layer masks for Enemy versus using GetComponent as shown in Ben’s video.

Even with only terrain and enemies, I did detect a bit of a performance hit using Ben’s version compared to using a simple layer mask. The rendering statistics show the amount of time taken to process and render one game frame, and my crummy laptop was taking around 0.75 ms longer per frame using GetComponent instead of the layer mask.

To be fair, this wasn’t really noticeable as a player, but I like to try and take the better performing options when I can. Plus, I think once I start adding more layers such as items to pickup, items to interact with, etc., those GetComponent calls could really start to add up.

Anyone have thoughts on this? My code below for reference, I also chose to pass the GameObject instead of Enemy component. This allows me to only call GetComponent if player actually clicks on the Enemy, also no longer need RPG.Characters in the CameraRaycaster class.

private bool RaycastForEnemy(Ray ray)
{
    RaycastHit hitInfo;
    bool hit = Physics.Raycast(ray, out hitInfo, maxRaycastDepth, enemyLayerMask);

    if (hit)
    {
        Cursor.SetCursor(attackCursor, attackHotspot, CursorMode.Auto);
        MouseOverEnemyEvent(hitInfo.collider.gameObject);
    }
    return hit;
}

+1

Besides the minimal gain in performance, there is another good reason to keep using a layer for the enemies.

In RaycastForEnemy() when we do:

Physics.Raycast(ray, out hitInfo, maxRaycastDepth);

without layer mask, the raycast stops at the first layer hit, so if there is something partially in front of the enemy, a tree for example, you’ll have trouble attacking the enemy.

Privacy & Terms