第一个控制整个门的脚本: 在此脚本中,我打电话:
LockDoor(i);
仅用于测试锁定所有门。
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);
}
}
每个门上附加的第二个脚本。每扇门都建有两个儿童门,这些儿童门可通过向两侧滑动来打开:
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;
}
}
在开始时,将门添加到列表中时,所有门均为空:
GameObject doorsParent = GameObject.Find("Wall_Door_Long_01");
foreach(Transform door in doorsParent.transform)
{
doors.Add(door.GetComponent<DoorHori>());
}
我要在HoriDoorManager脚本中获取的门结构和门的屏幕截图是Door_Left和Door_Right
为什么它为空?我应该为OnTriggerExit上的门列表创建新实例吗?比较:doorLockState = lockState;
是逻辑吗?
运行游戏时,所有门都锁着,但是我得到了null异常。
我解决了第一个问题:
由于脚本首先附加到了孩子,所以我正在检查孩子是否有父母。然后获取父对象,然后在该父对象上搜索特定的“ Wall_Door_Long_01”游戏对象,然后在“ Wall_Door_Long_01”游戏对象上进行搜索:
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>());
}
}
}
结果是,列表测试包含两个GameObjects Door_Left和Door_Right,并且列表门包含每个门中的两个脚本。
现在我不需要测试列表,但是我需要门列表来调用OpenDoor方法。