Question about Switch / Case syntax and the Update() method

Hello there!

I have a quick question, for anyone available who has the answer. Here is the code:

using UnityEngine;

public class CollisionHandler : MonoBehaviour
{
    GameObject other;
    
    void OnCollisionEnter(Collision other) 
    {
        switch (other.gameObject.tag)
        {
            case "Friendly":
                Debug.Log("We are at the home base.");
                break;
            case "Finish":
                Debug.Log("Woohoo! We made it to the finish!");
                break;
            case "Obstacle":
                Debug.Log("We hit an obstacle.");
                break;
            default:
                Debug.Log("Flying...");
                break;

        }
        
    }



}

My question is: How is it that this switch is checking for each case constantly? Wouldn’t it only be called once? Shouldn’t we include this switch statement in the Update() method so it “checks” for each case once per frame? It’s a bit confusing to me, any help or shedding some light on this is appreciated. Thanks!

This is something called a “callback”. That basically means that if a certain set of circumstances happen, then the unity engine calls this method OnCollisionEnter and includes the data, other which is of type Collision.

You don’t need to call it, the engine calls it when the object bumps into something with collider/rb.

4 Likes

Ahh, I see. That helps a lot, thanks!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms