Entyro
1
Hi!
I have a problem with my pickup script. I can’t find anything wrong with my code so some help would be appreciated.
When you go over a trigger tagged, for example “Battery”, a text pops up and when you press “E” it should go to your inventory. Everything works except it wont dissapear and go to the inventory. If I delete “if (Input.GetKeyDown(KeyCode.E))” it works fine, but I need that part of the code.
Does anyone know how to fix this little poblem?
var pickupText : UnityEngine.UI.Text;
var flashlight : Flashlight;
var inventoryScript : Inventory;
var pickupSound: AudioClip;
var batteryInRange : boolean;
var flashlightInRange : boolean;
function OnTriggerEnter (other : Collider)
{
if (other.gameObject.CompareTag("Battery"))
{
batteryInRange = true;
if (Input.GetKeyDown(KeyCode.E))
{
inventoryScript.batteries += 1;
other.gameObject.SetActive (false);
}
}
if (other.gameObject.CompareTag("Flashlight"))
{
flashlightInRange = true;
if (Input.GetKeyDown(KeyCode.E))
{
flashlight.enabled = true;
other.gameObject.SetActive (false);
}
}
}
function OnTriggerExit ()
{
batteryInRange = false;
flashlightInRange = false;
}
function Update ()
{
if (batteryInRange)
{
pickupText.text = "[E] PICK UP BATTERY";
}
if (flashlightInRange)
{
pickupText.text = "[E] PICK UP FLASHLIGHT";
}
}
I belive you need to use
“OnTriggerStay” not “OnTriggerEnter”, as OnTriggerStay gets called every frame while “other” is within the collider, while OnTriggerEnter only gets called once when it first makes contact with collider.