Search code examples
c#collision-detectionunity-game-enginecollider

Differentiating between player and other objects colliders during collision detection


I have a safe zone with colliders detecting if my player is inside or not by sending an event message. But there are a lot of other objects inside the safe zone.

To detect if my player is inside, I use:

void Start()
{
    if (player == null)
    {
        player = GameObject.Find("Gringan").GetComponent<Player>();
        Debug.Log("player = " + player.name);
    }
}

void OnTriggerEnter(Collider other)
{
    //else ...
    if (other.transform.parent.GetComponent<Player>() == player)
    {
        print("Collision detected with trigger object " + player.name);
        safe = true;
        m_Player.PlayerIsSafe.Send(safe);
    }
}

For others objects inside the safe zone, I get a null reference exception. (other objects don't need .parent and don't have a Player component...)

I would like to avoid that by detecting these items too without getting error messages. I would like to write something before the "//else" to only have my player in the next statement (if). I tried with tags and many several ways but can't get them to work.


Solution

  • A common solution here is to use tags to identify your objects, so you know what they are before you attempt a GetComponent() on them. This saves you processing time and avoids errors you might get trying to use non-existent components.

    For example, if you tag the top-level GameObject in your player object hierarchy with the tag "Player", you could write:

    void OnTriggerEnter(Collider other)
    {
        //else ...
        if (other.transform.root.CompareTag("Player")
            && other.transform.parent.GetComponent<Player>() == player)
        {
            print("Collision detected with trigger object " + player.name);
            safe = true;
            m_Player.PlayerIsSafe.Send(safe);
        }
    }
    

    Note: Thanks to short-circuiting with conditional operators in C#, you don't need to write multiple nested statements for the comparisons - if the CompareTag() fails, the subsequent GetComponent() won't be executed.

    Hope this helps! Let me know if you have any questions.