Check component instead of Tag

Better not teach beginners to use tags for cases like this, it’s a bad practice. Since we have a Player script only on player, would be easier to check if collided object has it. Same one line of the code:

void OnCollisionEnter(Collision collision) {
  if (collision.gameObject.TryGetComponent<Player>(out Player player)) {
    // it was a player!
  }
  
1 Like

Thanks @Bagumka this is great and appreciate the brains.

my code was originally

private void OnCollisionEnter (Collision collision)
{
    if (collision.gameObject.CompareTag("Player"))
    {
        Debug.Log("player hit dropper cube");
        GetComponent<MeshRenderer>().material.color = Color.red;
    }
}

But with your insight refactored to the below working just the same and being a cleaner version than before.

private void OnCollisionEnter (Collision collision)
{
    if (collision.gameObject.TryGetComponent<PlayerInput>(out PlayerInput playerInput))
    {
        Debug.Log("player hit dropper cube");
        GetComponent<MeshRenderer>().material.color = Color.red;
    }
}
1 Like

my point is - Tags should be never used in the code. They should be something that exist only in Editor for better Asset-management (for filtering in Asset-manager). You should never do CompareTag("tag") in the code.

1 Like

Privacy & Terms