Answer the question
In order to leave comments, you need to log in
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
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
}
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 questionAsk a Question
731 491 924 answers to any question