K
K
KeysCG2022-04-03 02:51:59
Unity
KeysCG, 2022-04-03 02:51:59

Why might the object not respond to the button click condition?

Good day!
There was such a problem that when I try to add a condition to a trigger (pressing a button), the object simply does not react at all. Without the click condition, everything works :(
Please help me understand how to do it correctly:

private void OnTriggerEnter(Collider other)
    {
            if (other.tag == "Player" && Input.GetKeyDown(KeyCode.F))
            {
                AddItem(items, amount);
                Destroy(gameObject);
            }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
K0TlK, 2022-04-03
@K0TlK

OnTriggerEnter is called once when the object enters the trigger. Accordingly, all these checks are performed once. Those. in one frame, the object that entered the trigger must have the player tag and the F button must be pressed. The first condition can be met if the tag is written correctly, but in order to observe the second, you need to press the F button simultaneously with entering the trigger, which is difficult to do . The smart guys will, of course, advise using OnTriggerStay, but you don't need to do this. You need to separate the input. You get something like this:

private void OnTriggerEnter(Collider other)
{
    if (other.TryGetComponent(out Player player))
    {
        PlayerInput.ActionButtonPressed += DoStuff;
    }
}

private void OnTriggerExit(Collider other)
{
    if (other.TryGetComponent(out Player player))
    {
        PlayerInput.ActionButtonPressed -= DoStuff;
    }
}

private void DoStuff()
{
    //Do stuff
}

OnTriggerEnter checks if the Player component is present on the object. It's the component, not the tag. There is no need to do checks on the tag, because these are strings and you can make a mistake in writing this string, do checks for the presence of a component. If the component exists, then we subscribe the required method to the ActionButtonPressed event. In OnTriggerExit, respectively, we unsubscribe. And in OnDestroy too, if the object is destroyed. You must always unsubscribe.
And a rough example of PlayerInput below:
public class PlayerInput : MonoBehaviour
{
    public static event Action ActionButtonPressed;


    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            ActionButtonPressed?.Invoke();
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question