Advertisement
Pro_Unit

DoorActivator

Sep 19th, 2021
1,213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.17 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. namespace DefaultNamespace
  4. {
  5.     public class DoorActivator : MonoBehaviour
  6.     {
  7.         private const string Player = "Player";
  8.         private static readonly int Close = Animator.StringToHash("Close");
  9.         private static readonly int Open = Animator.StringToHash("Open");
  10.        
  11.         public GameObject Canvas;
  12.         public Animator Door;
  13.  
  14.         private Animator _anim;
  15.  
  16.         private bool _canOpenDoor;
  17.         private bool _doorIsOpened;
  18.  
  19.         [SerializeField] private KeyCode _activationKey = KeyCode.E;
  20.  
  21.         private void Start()
  22.         {
  23.             _anim = Door.GetComponent<Animator>();
  24.         }
  25.  
  26.         private void Update()
  27.         {
  28.             if (Input.GetKeyDown(_activationKey) && _canOpenDoor && _doorIsOpened)
  29.             {
  30.                 _doorIsOpened = !_doorIsOpened;
  31.  
  32.                 if (_doorIsOpened)
  33.                     _anim.SetTrigger(Close);
  34.                 else
  35.                     _anim.SetTrigger(Open);
  36.  
  37.                 _doorIsOpened = false;
  38.             }
  39.         }
  40.  
  41.         private void OnTriggerStay(Collider other)
  42.         {
  43.             if (other.CompareTag(Player))
  44.             {
  45.                 Canvas.SetActive(true);
  46.  
  47.                 _canOpenDoor = true;
  48.             }
  49.         }
  50.  
  51.         private void OnTriggerExit(Collider other)
  52.         {
  53.             if (other.CompareTag(Player))
  54.             {
  55.                 Canvas.SetActive(false);
  56.  
  57.                 _canOpenDoor = false;
  58.             }
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement