The first script that control the whole doors: In this script I'm calling:
LockDoor(i);
Just for testing locking all the doors.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DoorsManager : MonoBehaviour
{
private List<HoriDoorManager> _doors = new List<HoriDoorManager>();
private void Start()
{
var doors = GameObject.FindGameObjectsWithTag("Door");
foreach(var door in doors)
{
_doors.Add(door.GetComponent<HoriDoorManager>());
}
for(int i = 0; i < _doors.Count; i++)
{
LockDoor(i);
}
// find all your doors and add them to the _doors collection
// alternatively expose the collection to the UI and build it there
}
public void LockDoor(int doorIndex)
{
_doors[doorIndex].ChangeLockState(true);
}
public void UnlockDoor(int doorIndex)
{
_doors[doorIndex].ChangeLockState(false);
}
}
The second script that attached to each door. And each door is built with two children doors that open by sliding to the sides:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class HoriDoorManager : MonoBehaviour
{
private bool doorLockState;
private List<DoorHori> doors = new List<DoorHori>();
private void Start()
{
GameObject doorsParent = GameObject.Find("Wall_Door_Long_01");
foreach(Transform door in doorsParent.transform)
{
doors.Add(door.GetComponent<DoorHori>());
}
}
void OnTriggerEnter()
{
if (doorLockState == false)
{
if (doors != null)
{
for(int i =0; i < doors.Count; i++)
{
doors[i].OpenDoor();
}
}
}
}
public void ChangeLockState(bool lockState)
{
doorLockState = lockState;
}
}
In the Start when it's adding the doors to the List all the doors are null:
GameObject doorsParent = GameObject.Find("Wall_Door_Long_01");
foreach(Transform door in doorsParent.transform)
{
doors.Add(door.GetComponent<DoorHori>());
}
A screenshot of a door structure and the doors I'm trying to get in the HoriDoorManager script are the Door_Left and Door_Right
Why it's null ? Should I make instance new instance for the List of doors on OnTriggerExit ? Comparing: doorLockState = lockState;
is logic ?
When running the game all the doors are locked but I'm getting the null exception.
I solved the first problem:
Since the script is attached to a child first I'm checking if the child have a parent. Then getting the parent then searching for the specific "Wall_Door_Long_01" GameObject on this parent and then making a foreach over the "Wall_Door_Long_01" GameObject:
private void Start()
{
if(transform.parent != null)
{
Transform parent = transform.parent;
var doorsParent = parent.Find("Wall_Door_Long_01");
foreach(Transform door in doorsParent)
{
test.Add(door);
doors.Add(door.GetComponent<DoorHori>());
}
}
}
The result is that the List test contains two GameObjects Door_Left and Door_Right and the List doors contains the two scripts from each of the doors.
Now I don't need the test List but I do need the doors List to be able to call the OpenDoor method.