Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

I need help with a door script.

Discussion in 'Scripting' started by shadystyle84, Dec 13, 2015.

  1. shadystyle84

    shadystyle84

    Joined:
    Sep 13, 2015
    Posts:
    12
    I need to make my door a locked door that states it is locked and allow my player to open it only when he has the key, that is in the scene. Below is my door script as of now where my player can open it at will.

    using UnityEngine;
    using System.Collections;

    public class Door : MonoBehaviour {

    public GameObject hinge;

    Animator anim;

    void Start () {
    anim = hinge.GetComponent<Animator>();

    }

    void OnTriggerEnter (Collider entity) {
    if (entity.tag == "Player") {
    print ("The PlayerMapIcon has entered the OnTriggerEnter.");
    }
    }

    void OnTriggerStay(Collider entity){
    if (entity.tag == "Player") {
    if(Input.GetKeyUp (KeyCode.E)){
    anim.SetBool ("interact", true);
    print ("The Player has interacted with the door.");
    }
    }
    }

    void OnTriggerExit(Collider entity){
    if (entity.tag == "Player") {
    print ("The Player has left the trigger.");
    }
    }
    }
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    How many door/key combinations are you looking to support? How are you "holding" the key(s)?
     
  3. Sose

    Sose

    Joined:
    Dec 10, 2015
    Posts:
    27
    Supporting a single key is the easiest. Simply add a public variable to your player script (or make another script like KeyHolder.cs)

    Code (csharp):
    1.  
    2. //in KeyHolder.cs
    3. public bool GotKey = false;
    4.  
    5. OnTriggerEnter(Collider e) {
    6.   if(e.tag == "Key") {
    7.     GotKey = true;
    8.   }
    9. }
    10.  
    11. //in door script
    12. if(entity.GetComponent<KeyHolder>.GotKey) {
    13.   //he has the key!
    14. }
    15.