您应该使用该GetComponentsInChildren
方法而不是GetComponentInChildren
,以便您可以从中获取一个collider
s 数组,您可以在该数组上执行 aforeach
以检查sbounds
是否相交。
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
此而已。
然后,就在实例化之前,您可以bounds
通过在内部循环来检查List
a foreach
,检查会快很多。
====================================
编辑:
好的,这是交易。首先,将这些行添加到您的World
游戏对象脚本中(我猜您调用了 class 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>());
}
差不多就是这样。;)