- Home /
How to call OnTriggerEnter2D
Hello! So I am needing to call OnTriggerEnter2D once you press a key. Pretty much I'm making where if a sword is inside an enemy, you then need to press L to destroy it. This is my code so far:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class SwordController : MonoBehaviour {
void OnTriggerEnter2D (Collider2D other) {
Destroy (other.gameObject);
}
}
Please help, thanks!
Answer by Darkforge317 · Nov 28, 2017 at 06:40 AM
What you're doing is using OnTriggerEnter2D.
This is incorrect. OnTriggerEnter2D only runs when an object enters the trigger.
Therefore you need to press L on the exact same frame that the enemy enters your trigger... Unrealistic for a human's reaction time.
Try this instead
private void OnTriggerStay2D(Collider2D collision)
{
if(Input.GetKeyDown(KeyCode.L))
{
Destroy(collision.gameObject);
}
}
The difference between these two is that OnTriggerStay2D will be called every frame that your enemy is inside the trigger, instead of just being called on the first frame.
Answer by Mehul-Rughani · Nov 28, 2017 at 04:44 AM
Hope you are looking for this
void OnTriggerStay2D(Collider2D other){
if(Input.GetKeyDown(KeyCode.L)){
Destroy(other.gameObject)
}
}
Answer by Carson365 · Nov 28, 2017 at 02:59 AM
Hmmm. I also tried that before and it didn't work. Without the "if" statement, it works fine. I'm not sure why it isn't working still....
Answer by sethuraj · Nov 28, 2017 at 05:02 AM
Hi, Try like this.
//Boolean to check if sword is inside or not
bool m_IsSwordInside = false;
//Update is called once per frame
void Update()
{
if(Input.GetKeyUp(KeyCode.L) && m_IsSwordInside)
{
Destroy(other.gameObject);
}
}
void OnTriggerEnter2D(Collider2D other)
{
//State sword is inside
m_IsSwordInside = true;
}
void OnTriggerExit2D(Collider2D other)
{
//State sword is no longer inside
m_IsSwordInside = false;
}
Hope it helps!