Home > Mobile >  When i used OnTriggerEnter2D with Input.GetKey the input won't work
When i used OnTriggerEnter2D with Input.GetKey the input won't work

Time:07-13

When i press the key the the scene won't load, when i remove the input statemen, it works. can anyone help me ?

void OnTriggerEnter2D(Collider2D other)
{
    if(Input.GetKey(KeyCode.X)){
        Loader.Load(Loader.Scene.Shop);
    }
}

CodePudding user response:

This is because OnTriggerEnter2D method is called only once when the obstacle enters the collider's area. As soon as the obstacle enters, the code inside this method is read, and it instantly checks for the input, that too only once. That's the reason the code inside the if statement isn't read.

To take input when there's a trigger, have a boolean that decides whether the input from the user has to be taken or not.

private bool isTriggered = false;

In OnTriggerEnter2D method, set this boolean to true

void OnTriggerEnter2D(Collider2D other)
{
    isTriggered = true;
}

Check for user input in Update() method only when the trigger happened

void Update()
{
    if(isTriggered)
    {
        if(Input.GetKey(KeyCode.X))
        {
            Loader.Load(Loader.Scene.Shop);
        }
    }
}

Don't forget to set isTrigger to false when the obstacle has exited the collider's area

void OnTriggerExit2D(Collider2D other)
{
    isTrigger = false;
}
  • Related