- Home /
Question by
IamNomad_ · Jan 11, 2020 at 09:35 PM ·
c#collidertriggerontriggerstay
Work around for onTriggerStay?
I'm attempting to make a script that gets rid of a gameobject when you're colliding with it's trigger and press the E key. The only way I've found so far to do this is by using onTriggerStay, but since it doesn't call for this on every frame, I've found it to be less than helpful.
void OnTriggerStay(Collider other)
{
if (Input.GetKeyDown(KeyCode.E) && (other.gameObject.tag == "Item"))
{
other.gameObject.SetActive(false);
interactIcon.SetActive(false);
}
}
I've heard about the workaround by using a boolean and setting it to true on enter and false on exit, but I'm not sure how I'm intended to refer to the trigger I'm colliding with without it being within the void onTriggerEnter/Exit/etc.
Comment
Best Answer
Answer by Hellium · Jan 11, 2020 at 11:49 PM
private GameObject collidingItem;
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Item"))
collidingItem = other.gameObject;
}
void OnTriggerExit(Collider other)
{
if (other.gameObject == collidingItem)
collidingItem = null;
}
void Update()
{
if(collidingItem != null && Input.GetKeyDown(KeyCode.E))
{
collidingItem.SetActive(false);
interactIcon.SetActive(false);
}
}
I appreciate it!
Though, to get it to work, I had to switch it to this ins$$anonymous$$d, as it would give an error.
collidingItem = other.gameObject;