How2 Open Doors in Unity Using Proximity

Help keep Nerd Sherpa funded by contributing on PayPal. Thank you for supporting us!

This code will open and close a door when the player collider intersects with the door prefab collider. The player will use the “e” key to trigger the door animation.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class DoorController001 : MonoBehaviour
{
    bool isOpen = false; //is the door open? 
    bool isNextToDoor = false;//is the player next to the door? 
    public Animator DoorHing001;

    void Start()
    {
        //door.GetComponent<Animator>(); 
    }

    void Update()
    {
        if (isNextToDoor == true && Input.GetKeyDown(KeyCode.E) && isOpen == false)
        {
            DoorHing001.SetBool("Open", true);
            isOpen = true;
        }

        else if (isNextToDoor == true && Input.GetKeyDown("e") && isOpen == true)
        {
            DoorHing001.SetBool("Close", true);
            DoorHing001.SetBool("Open", false);
            isOpen = false;
        }
        if (isOpen == true)
        {
            DoorHing001.SetBool("Close", false);
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        isNextToDoor = true;
    }

    private void OnTriggerExit(Collider other)
    {
        isNextToDoor = false;
    }
}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments