Problem with "Input.GetKeyDown"

I have this code

void OnTriggerEnter(Collider col)
    {
        if (Input.GetKeyDown (KeyCode.E))
        {
            Destroy (gameObject);
            carSettings.pizzaAmount--;
        }   
    }

Without the “if (Input.GetKeyDown (KeyCode.E))” the code works 100% but with it, then it doesn’t work, what is up with that ? :wink:

OnTriggerEnter and GetKeyDown are frame-specific, so the collider would have to be entered in the exact same frame that the user pressed E in order for the code to work. It is possible but will be quite difficult to do. Is this what you intended?

ETA: To word it better, both are only called once, on a single frame.

If you’re wanting it to do something like destroy the object at any point after the OnTriggerEnter event has been called, have a bool set to ‘true’ during that event, then in Update, check for GetKeyDown, and then have it destroy only if that bool is true.

In general you should only use GetKeyDown and similar things in Update anyway.

Nesseggman, I get your point.

The script is attachted to a dropzone. When you have entered the dropzone, I want to press E, so i “drop” something, and the dropzone deletes.

Do you follow me?

I see, yeah, I was editing my post as you replied, so I think my edited post above should provide a solution. You can also set the bool back to ‘false’ in the OnTriggerExit event if you need it to only work when you press E while over the dropzone.

Just read your editet post! That seems like a great solution.

Im gonna make that and i will come back with a result

Nesseggman thanks for the help :wink: It works!

The final code :wink:

using UnityEngine;
using System.Collections;


public class delivery : MonoBehaviour {

    // Variable definitions
    bool EnableE = false; // Activate "e" function to dropoff

    void Update ()
    {
        if (EnableE)
        {
            if (Input.GetKeyDown (KeyCode.E))
            {
                Destroy (gameObject);
                carSettings.pizzaAmount--;
            }
        }
    }

    // Enable EnableE when Player enters Dropoff Zone
    void OnTriggerEnter(Collider col)
    {
        EnableE = true;
    }
    // Disable EnableE when Player exit Dropoff Zone
    void OnTriggerExit(Collider col)
    {
        EnableE = false;
    }
}
1 Like