Pick up key and unlock a locked door

Hello everyone,

I’m trying to get the Player to pick up a key (at the moment a capsule for testing reasons) and open a door (at the moment a cube for testing reasons) that will warp the Player to the next level.

To pick up the key, the player must walk up to it and press E. The key is then stored in an inventory (currently very small).
With the key, the player should be able to move on to the next level, but without it, it shouldn’t be possible.

Here’s my code for the two scripts I’ve written.

PlayerInventory.cs (attached to the First Person Controller (Player)):

using UnityEngine;
using System.Collections;
using System.Linq;

public class PlayerInventory : MonoBehaviour {

public string[] Inventory = new string[1];

	void Start ()
	{
		Inventory[0] = "";
	}
	
}

and then PlayerInventoryCheck.cs (attached to the “door”):

using UnityEngine;
using System.Collections;
using System.Linq;
using UnityEditor;

public class PlayerInventoryCheck : PlayerInventory {

	void Update () 
	
	{
	
	if (Input.GetKeyDown(KeyCode.E))
	{
		
		string correctKey = "Captain's Key";
		foreach(string x in Inventory)
	
		{
			if (x.Contains(correctKey))
				{
					Application.LoadLevel ("Captain's Quarters");
				}
			else
				{
					Debug.Log("Wrong Key");
				}
		}
	}	
	}
}

and finally PickUpItem.cs (attached to the key):

using UnityEngine;
using System.Collections;
using System.Linq;
using UnityEditor;

public class PickUpItem : PlayerInventory {

	void Update ()
	{
	
	if (Input.GetKeyDown(KeyCode.E))
	{
		Debug.Log("You picked up a key");
		Inventory[0] = "Captain's Key";
		Debug.Log("You picked up a key");
	}	
	}
}	

I get no errors in the console, but whenever I press E (wherever I am in the map), it just debugs in the console as: “Wrong Key”.
This should only be possible when inside the box-collider of the door (which the ‘Is Trigger’ is checked, by the way).

Also, it doesn’t work to actually pick the key up because of this.

Any idea on what might be wrong here? Been sitting with this all day and I’m getting very dizzy.

Thank you.

I’m aware of that, but let’s call the box a door for now. Right. You haven’t got any collision detection. That’s your problem. Essentially, all of this code in your Update sequence is run constantly, in a loop, not just when you’re inside the object it’s on. Nowhere in your code have you told it to interact with the player at all, you’ve just told it what to do when you press the E key. It will do exactly what you’ve told it to - i.e. run the code when you press the E key. You haven’t given it any conditions, such as “if the player is inside the door”, which is why it doesn’t test for that. I suggest you look at some beginner tutorials, as it’s quite obvious you’re new at this.