1
votes

I'm new at Unity, so.. :) Im making 2D game, my character should enter the car by pressing F, Unity should load a new scene. There's my C# code:

void OnTriggerEnter2D(Collider2D other)

{
    if (other.tag == "Player")
    {
        //Debug.Log("TRIGGER");
        if (carTitle == "98" && Input.GetKeyDown(KeyCode.F))
        {
            SceneManager.LoadScene("NewScene");
            //Debug.Log("TRIGGER 98");
        }
    }
}

There's a problem. I used two Debug lines to see what exactly happens here. The first one is saying "TRIGGER" when my car is colliding with Player, it works fine. But the second one is keeping silent. Every car has a specific number public string carTitle, and IF my car is number 98 AND player hits the button F when car and player collide, it should load a new scene. Am I right? But nothing happens.

2
Put a breakpoint on your second if statement and see if the actual values are what you expect them to be. - PhillipXT
Yeah, the carTitle = 98, KeyCode = F, but still nothing happens. BUT! If i remove my Input.GetKeyDown(KeyCode.F), leaving only carTitle check - it works fine. Something wrong with reading a key. - Den
This script is attached to my car, not to Player. Does it matter? - Den

2 Answers

1
votes

I see you have solved the problem, but I'd like to take a moment to explain why it wasn't working:

  • OnTriggerEnter2D will only be executed during one cicle, right as the collider enters the trigger.

  • Input.GetButtonDown(), will only be true one cycle, right when the key is pressed down.

So, for the conditions to meet, you should be pushing the "F" key in the EXACTLY same cycle as you enter the trigger. Which of course is extremelly impractical.

If you want to change scene when the player presses F while on the trigger, using the OnTriggerStay2D isthe callback you are looking for.

If you want to change scene, only when you enter the trigger as you are keeping the F key down, you should use Input.GetButton()

0
votes

I used OnTriggerStay2D, so now it works fine.

 void OnTriggerStay2D(Collider2D other)

{
    if (other.tag == "Player" && Input.GetButtonDown("Use"))
    {

        if (carTitle == "98")
        {
           SceneManager.LoadScene("NewScene");
        }
    }

}