Script Problem 2

So I fixed the error in my last line of code, but now I have another problem. This script is supposed to allow the Player to collect a key. Then, the Player is supposed to enter a trigger and click to open a door. However, the Player can open the door now without collecting the key. Here are the scripts: Can someone tell me what I did wrong?

Key Script - Attached to Player

var keyObject : GameObject;
var keypickup : AudioClip;
var inRange;
public var Door : GameObject;
public var Locked : GameObject;

function OnTriggerEnter(Other : Collider) {
	if(Other.gameObject.tag == ("key"))
	{
		inRange = true;
	}
}

function OnTriggerExit(Other : Collider) {
	if(Other.gameObject.tag == ("key"))
	{
		inRange = false;
	}
}

function OnTriggerStay() {
	if(Input.GetButton("Fire1") && inRange == true)
	{
		Debug.Log("Key has been collected");
		audio.clip = keypickup;
		audio.Play();
		Destroy (keyObject);
		key();
	}
}

function key()
{
	Door.GetComponent("Door").enabled = true;
    Locked.GetComponent("Locked").enabled = false;
}

Door Script - Attached to Door

function OnTriggerStay() {
	if(Input.GetButtonDown ("Fire1"))
	{
		door();
	}
}

function door() {
	animation.Play("open01");
	debug();
}

function debug() {
	if(Input.GetButtonDown ("Fire1"))
	{
		Debug.Log("Door");
	}
}

Locked Door Script - Attached to Door

var AudioFile : AudioClip;

function OnTriggerStay() {
	if(Input.GetButtonDown ("Fire1"))
	{
		audio.clip = AudioFile;
		audio.Play();
	}
}

I made sure the door script was unchecked when I ran the game, but no use.

Hi, Just a suggestion, why don’t you just use a bool value to set if the player has a key (set to true in your key() method), and when the player triggers the door, the door script will check if the player has key before it can open?

You should have a ‘has key’ boolean that you set to true when you enter the key object’s trigger. You can then check if you have this key boolean set when trying to open the door.

As a side node you shouldn’t use var for all of your declarations, it makes the code harder to read.

The door will always open.

  1. The door script does not check for any conditions that are used.
  2. If you go near the door and click the mouse the door will open. As the animation is called if you click it.

What are you suppose to do ?

  1. Use GetComponent to access another script on a different object.
  2. Check the boolean used in the DoorScript which is assigned in the KeyScript.

This is as simple as adding another boolean to the AddTriggerStay()

var Door: GameObject;
KeyScript KeyScriptPointer;
void Start()
{
KeyScriptPointer = Door.GetComponent("KeyScript");

}
void OnTriggerStay()
{
if(Input.GetButtonDown ("Fire1") && KeyScriptPointer.inRange)
{
door();
}
}