1

So, I am making a game... And on that game I have a door and a Key... The door is locked but when you catch the key the door is unlocked...

I have 2 scripts... The script which belongs to the door is Door.js and the script that belongs to the key is Key.js

EmptyObject > Key > Key.js Door > Door.js

In my key.js I have this codes:

  public var hasKey : boolean;

  function OnTriggerEnter (other : Collider){

  if (other.gameObject.tag == "Player") {
   hasKey = true;
 }

and on my Door.js I have this codes:

   var openDoor : boolean;

  function OnTriggerEnter (other : Collider){

   if (other.gameObject.tag == "Player" && hasKey== true) {
     openDoor = true;

}

Thanks for the help.

1 Answer 1

1

attach a script to your player and add a hasKey variable to that script because the player has the key not the door and use getComponent to get the variable from it
remember that the hasKey variable must be public to be accessible by other scripts
I named the script that is attached to the Player PlayerStuff

for key

   function OnTriggerEnter (other : Collider){

      if (other.gameObject.tag == "Player") {
      other.gameObject.GetComponent.<PlayerStuff>().hasKey= true;
     }
}

for door

 var openDoor : boolean;

  function OnTriggerEnter (other : Collider){

   if(other.gameObject.tag == "Player" && other.gameObject.GetComponent.<PlayerStuff>().hasKey== true){
     openDoor = true;
  }
}

there is another version of getComponent it is like this if the first one doesn't work use the one below instead

   other.gameObject.GetComponent(PlayerStuff)

or

 other.gameObject.GetComponent("PlayerStuff")
Sign up to request clarification or add additional context in comments.

3 Comments

The bottom note has to be other.gameObject.GetComponent("PlayerStuff"). This version should be avoided though if possible.
other.gameObject.GetComponent(PlayerStuff) is from the documentaion here
Yes, but that has either GetComponent<Type>() or GetComponent("Type") (with a string). (It says your version in the declaration, but the actual example is different.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.