3
\$\begingroup\$

I'm making an RPG in Unity3D and I am trying to make a script for a chest to open. So I built this script! But it doesn't work. I just want some help fixing this script.

#pragma strict
var Text : GameObject;
var OpenedChest : GameObject;
var CurrentChest : GameObject;

function OnTriggerEnter()
{
    Text.SetActive(true);
    if (Input.GetKeyDown("e"))
    {
        CurrentChest.SetActive(false);
        OpenedChest.SetActive(true);
    }
}

function OnTriggerExit()
{
    Text.SetActive(false);
}

I get no compiler errors. When I go into the collider that triggers the text, that works, but what doesn't is when I press E to open the chest. It doesn't activate the other chest. What is wrong with my script?

\$\endgroup\$
6
\$\begingroup\$

The issue in your code is that you only check for the key press in the OnTriggerEnter function, which only gets called when the collider enters the trigger. What you probably want to do instead is check for the keypress inside the OnTriggerStay function, which gets called while the collider lies inside the trigger.

\$\endgroup\$
  • \$\begingroup\$ Always happy to help, glad to hear that this solved the problem! \$\endgroup\$ – Tyyppi_77 Jul 17 '16 at 16:11
3
\$\begingroup\$

Is the script attached to the game object of one of the two chests CurrentChest and OpenChest? Then keep in mind that deactivating a game object also deactivates all scripts attached to it. That means any events on them won't fire anymore. You likely only want to disable specific components of the chests.

\$\endgroup\$
  • \$\begingroup\$ I know that. Infact I created an empty game object and put the 2 chests in there with the game object having the script on it. Still nothing works. But someone already helped with it. Thanks anyway. \$\endgroup\$ – user80678 Jul 17 '16 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.