Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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);
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading