- Home /
How to Specify a Collider in OnTriggerStay function?
I have Capsule and Box Colliders in NPC GameObjects and Player GameObject. I use Box Colliders as trigger, because I want to use OnTriggerStay to interact Player and NPCs
However, I dont want to repeat same action on one NPC, therefore I want to disable the Box Collider of NPC I interacted with, but after i do this via script, Player and NPC can interact again(even without triggers)
I want to specify the Box Collider in OnTriggerStay function. How can I achieve this?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerInteraction : MonoBehaviour
{
private GameObject triggeringNPC;
private bool triggering;
public GameObject pickpocketText;
public GameObject PickpocketingText;
public float timer = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (triggering)
{
pickpocketText.SetActive(true);
PickpocketingText.SetActive(false);
if (Input.GetKey(KeyCode.F))
{
timer += Time.deltaTime;
}
if(timer>0.1f)
{
pickpocketText.SetActive(false);
PickpocketingText.SetActive(true);
}
if (Input.GetKeyUp(KeyCode.F) && timer < 3)
{
print("pickpocket failed");
timer = 0;
}
if (Input.GetKeyUp(KeyCode.F) && timer >= 3)
{
print("++++++money" + triggeringNPC);
timer = 0;
triggeringNPC.GetComponent<BoxCollider>().enabled = false;
GetComponent<BoxCollider>().enabled = false;
}
}
else
{
pickpocketText.SetActive(false);
PickpocketingText.SetActive(false);
}
}
void OnTriggerEnter(Collider other)
{
if(other.tag == "NPC")
{
triggering = true;
triggeringNPC = other.gameObject;
}
}
private void OnTriggerStay(Collider other)
{
if(other.tag == "NPC")
{
triggering = true;
triggeringNPC = other.gameObject;
if (Input.GetKey(KeyCode.F))
{
pickpocketText.SetActive(false);
}
}
}
void OnTriggerExit(Collider other)
{
if (other.tag == "NPC")
{
triggering = false;
triggeringNPC = null;
}
}
}
Answer by Chris333 · Apr 05, 2019 at 09:34 AM
You are setting "triggering" to false only in the OnTriggerExit method but if you disable the collider after a successful interaction with the npc, OnTriggerExit will never be called because you disabled the collider for the detection. So "triggering" will stay true. So you should set "triggering" to false when you disabled the collider.
if (Input.GetKeyUp(KeyCode.F) && timer >= 3)
{
print("++++++money" + triggeringNPC);
timer = 0;
triggeringNPC.GetComponent<BoxCollider>().enabled = false;
GetComponent<BoxCollider>().enabled = false;
triggering = false;
}