Pickable item to unlock doors (Being able to proceed next scene)

Hi everyone, I’m currently working on a horror game and after hours of building my scene, I got stuck with one little thing: Picking up an key and being able to unlock a door to change scene, and if I don’t have a key, I want to restrict the action of changing scenes.

For now on, my key already has a Sphere collider with the “Is Triggered” checked.

Here’s a 2 screenshots of my Key and the door:

Key:

Door:

10698-door_finish.png

If you guys have a good way to solve this question or if you need more info, please post them below! I will reply your answers/comments quick and fast.

Thanks!

~crusherxman

So your key has a sphere collider set to IsTrigger.

On your player you have:

var hasKey:boolean = false;;

function OnTriggerEnter(other:Collider){
  if(other.collider.tag == "Key"){
    hasKey = true;
    Destroy(other.gameObject);
  }
}

function Update(){
  var hit :RaycastHit;
  if(Pyhsics.Raycast(transform.position, transform.forward, hit, 2)){
    if(hit.collider.tag == "Door" && hasKey && Input.GetKeyDown(KeyCode.Space)){
      Application.LoadLevel("nextLevel");
    }
  }
}

Hopefully I did not miss anything…The idea is simple, if you collect the key you get the boolean and you need the boolean to open the door.

EDIT:

I actually, I realize I just reformulated the other answer already given…

I will try to make an example code which hopefully will work in your case:

var hasKey = false;

function Update(){
if(Input.GetKeyDown(KeyCode.E)){ //If E is pressed
  var hit : RaycastHit;
  if (Physics.Raycast (transform.position, transform.forward, hit, 50)) { // Sends out a raycast to check if something is in front of you
    if(hit.transform.tag == "Key"){ // If the object in front of you has the tag Key
      Destroy(hit.transform.gameobject);//Destroy Key Object
      hasKey = true;
    }else if(hit.transform.tag == "Door"){ //Checks if the gameobject you're looking at has the tag Door
      if(hasKey)
        hit.transform.SendMessage("Unlock"); //Calls the function Unlock on the door
    }
  }
}
}

Add this script to your camera, Add a function Unlock to the door which actually opens the door or removes a lock, … and add the tag Door to the door and Key to the key. Or you change the code to match your case.

Hope it works for you if not let me know.