Some of my doorways were 2 grids wide so I refactored and extended the Door class with a LargeDoor class that overrides the start method to set both grids under it as interactable.
I also set the colliders to be disabled when the doors are open so that they can be shot through, as suggested in another post.
Since this code is using the IInteractable Interface I thought it would be better to post it under this lesson instead of the last one to reduce confusion.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class LargeDoor : Door
{
protected override void Start()
{
gridPositionList = new();
GridPosition leftDoorGridPosition = LevelGrid.Instance.GetGridPosition(transform.position + Vector3.right * 0.01f);
GridPosition rightDoorGridPosition = LevelGrid.Instance.GetGridPosition(transform.position + Vector3.left * 0.01f);colliderArray = GetComponentsInChildren<Collider>(); gridPositionList.Add(leftDoorGridPosition); gridPositionList.Add(rightDoorGridPosition); LevelGrid.Instance.SetInteractableAtGridPosition(leftDoorGridPosition, this); LevelGrid.Instance.SetInteractableAtGridPosition(rightDoorGridPosition, this); if (isOpen) { OpenDoor(); } else { CloseDoor(); } }
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class Door : MonoBehaviour, IInteractable
{
[SerializeField] protected bool isOpen;protected List<GridPosition> gridPositionList; protected Collider[] colliderArray; bool isActive; float timer; Animator animator; Action onInteractComplete; void Awake() { animator = GetComponent<Animator>(); } protected virtual void Start() { gridPositionList = new(); GridPosition gridPosition = LevelGrid.Instance.GetGridPosition(transform.position); gridPositionList.Add(gridPosition); colliderArray = GetComponentsInChildren<Collider>(); LevelGrid.Instance.SetInteractableAtGridPosition(gridPosition, this); Pathfinding.Instance.SetIsWalkableGridPosition(gridPosition, true); if (isOpen) { CloseDoor(); } else { OpenDoor(); } } void Update() { if (!isActive) { return; } timer -= Time.deltaTime; if (timer <= 0f) { isActive = false; onInteractComplete?.Invoke(); } } public void Interact(Action onInteractComplete) { this.onInteractComplete = onInteractComplete; isActive = true; timer = 0.7f; if (isOpen) { CloseDoor(); } else { OpenDoor(); } } protected void OpenDoor() { isOpen = true; animator.SetBool("IsOpen", isOpen); foreach (GridPosition gridPosition in gridPositionList) { Pathfinding.Instance.SetIsWalkableGridPosition(gridPosition, true); } foreach (Collider collider in colliderArray) { collider.enabled = false; } } protected void CloseDoor() { isOpen = false; animator.SetBool("IsOpen", isOpen); foreach (GridPosition gridPosition in gridPositionList) { Pathfinding.Instance.SetIsWalkableGridPosition(gridPosition, false); } foreach (Collider collider in colliderArray) { collider.enabled = true; } }
}