Referencing Player in OnTriggerEnter

Just a quick question about the way @sampattuzzi referenced the Player in the OnTriggerEnter:

        void OnTriggerEnter(Collider other)
        {
            var player = GameObject.FindGameObjectWithTag("Player");
            if(other.gameObject == player) {
                pickup.PickupItem();
            }
        }

Where as I used this method:

        void OnTriggerEnter(Collider other)
        {
            if(other.tag == "Player") pickup.PickupItem();
        }

Is there a something I’m missing with mine? It works fine, but I was wondering if there was something I was missing.

Thanks so much!

Julian Boardman

2 Likes

No, yours is better, actually.
Let’s speed it up even a bit more:

void OnTriggerEnter(Collider other)
{
    if(other.gameObject.CompareTag("Player") pickup.PickupItem();
}
2 Likes

Ooh! Nice! I didn’t know there was a CompareTag method! I like it!

For many of these strings comparisons I will extract out the string and create a const like:

const string PLAYER = "Player";

Thanks so much, Brian!

Julian

I wrote an extension method for this exact purpose:

public static class GameObjectExt
{
    public static bool IsPlayer(this GameObject gameObject)
    {
        return gameObject.CompareTag("Player");
    }
}

Allows you to just write:

if (gameObject.IsPlayer()) ...
2 Likes

That’s a nice one! Well done.
We’re not covering Extension methods in this course, but they are an excellent way to extend classes and add some extra muscle to your code.

1 Like

Privacy & Terms