您应该使用GetComponentsInChildren 方法而不是GetComponentInChildren,这样您就可以从中获取colliders 的数组,您可以在该数组上执行foreach 来检查bounds 是否相交。
IE:
m_Collider2 = spawnpoints [i].GetComponent<Collider>();
m_Collider = world.GetComponentsInChildren<Collider>();
foreach(Collider objCollider in m_Collider) {
if (objCollider.bounds.Intersects(m_Collider2.bounds))
{
Debug.Log("Bounds intersecting");
break;
}
}
但是,这种处理方式对 CPU 来说是很重的,因为 GetComponent 方法真的很慢,所以如果可能的话,它们的使用应该限制在 Awake 和 Start 方法中。
解决这个问题的另一种方法是在开始时创建一个List<Collider>,并将您的 World 游戏对象的起始子对象添加到它。如果另一个实例被实例化,只需 Add 将其添加到您的列表中,如果它已被销毁,则只需 Remove 它。
然后,就在实例化之前,您可以通过在List 中循环使用foreach 来检查bounds,检查会快很多。
===================================
编辑:
好的,这就是交易。首先,将这些行添加到您的 World 游戏对象脚本中(我猜您将类称为 World):
using UnityEngine;
using System.Collections.Generic; //Namespace needed to use the List type
public class World : MonoBehaviour {
//The list which will hold references to the children game objects colliders
public List<Collider> childrenColliders;
private void Start() {
//Code used to populate the list at start
childrenColliders = new List<Collider>(GetComponentsInChildren<Collider>());
}
现在,因为在生成新对象的脚本中已经有一个 world 变量,它包含对 World 类的引用:
foreach(Collider coll in world.childrenColliders) {
if (coll.bounds.Intersects(m_Collider2.bounds))
{
Debug.Log("Bounds intersecting");
break;
}
}
当然,正如我之前所说,记得将新生成的游戏对象的对撞机添加到列表中:
void AddNewGameObject() {
// spawnPoint is the transform.position Vector3 you'll use for the new game object
var newGameObject = Instantiate(yourObjectPrefab, spawnPoint, Quaternion.identity, world.transform);
world.childrenColliders.Add(newGameObject.GetComponent<Collider>());
}
差不多就是这样。 ;)