Reputation: 201
I'm trying to create a simple melee attack in Unity but am having trouble with the code. I have the following written:
public class meleeAttack : MonoBehaviour
{
void Start()
{
}
void Update()
{
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
print("What's up!!!");
}
}
That works fine by itself, however, I want to make it so the message only pops up when the player presses a key. I tried adding the following to the OnTriggerEnter method:
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player" && Input.GetKeyUp(KeyCode.F))
print("What's up!!!");
}
The issue is that now the message will no longer show up, even if I'm pressing the F key. Is there a way I can incorporate this code in order to call the message only when the player presses the F key and is in contact with the gameObject?
Upvotes: 1
Views: 948
Reputation: 10571
You can use OnTrigggerStay instead of onTriggerEnter and you can avoid speical bool in Update event.
OnTriggerStay is called almost all the frames for every Collider other that is touching the trigger
something like this, you required
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player" && Input.GetKeyUp(KeyCode.F))
print("What's up!!!");
}
Upvotes: 0
Reputation: 16540
You will need to do the GetKeyUp in the update loop and set a boolean flag that is then checked for in the OnTriggerEnter.
Or vise-versa depending on your timing requirements (ie. set the boolean flag in OnTriggerEnter, and check for it within the Update loop). [I'd likely do it this way given your description]
The problem you have is OnTriggerEnter will only fire once, and so it won't keep polling the keyboard for changes in the key state, which is why you need a check in the Update loop.
Upvotes: 1