c# - 如何让所有游戏对象检查哪些游戏对象有碰撞器,哪些游戏对象根本没有碰撞器?
问题描述
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class GetComponents : MonoBehaviour
{
public List<Collider> allColliders = new List<Collider>();
private List<GameObject> allObjects = new List<GameObject>();
// Start is called before the first frame update
void Start()
{
allObjects = FindObjectsOfType<GameObject>().ToList();
foreach (GameObject go in allObjects)
{
foreach (Collider collider in go.transform.GetComponents<Collider>())
{
allColliders.Add(collider);
}
}
}
// Update is called once per frame
void Update()
{
}
}
最后,我想要两个列表,可能会将它们写入文本文件,例如输出格式:
Wall1 -- BoxCollider,CapsuleCollider
Door22 -- 没有碰撞器
Door10 -- BoxCollider
像这样的东西。目标是找出哪些游戏对象有碰撞器,哪些游戏对象根本没有碰撞器。
解决方案
最简单的方法是获取对象上的所有对撞机,然后检查返回数组的长度,如果为 0,则没有对撞机,否则有:
void Start()
{
allObjects = FindObjectsOfType<GameObject>().ToList();
foreach (GameObject go in allObjects)
{
var colliders = go.transform.GetComponents<Collider>();
int length = colliders.Length;
if (length == 0)
{
Debug.Log(string.Format("{0} - No Colliders", go.name));
}
else
{
//composes a list of the colliders types, this will print what you want e.g. "Wall1 - BoxCollider, MeshCollider"
string colliderTypes = string.Empty;
for (int i = 0; i < length; i++)
{
colliderTypes = string.Format("{0}{1}", colliderTypes, colliders[i].GetType().Name);
if (i != (length - 1))
{
colliderTypes = string.Format("{0}, ", colliderTypes);
}
}
Debug.Log(string.Format("{0} - {1}", go.name, colliderTypes));
}
}
}
请注意,Collider
该类是 3D 碰撞器的基础,如果您还需要检查 2D 碰撞器,则获取所有Collider2D
组件并执行相同的操作。
推荐阅读
- ruby - Ruby:如何标记现有的 AWS VPC
- c++ - 将 uint8_t 数组转换为字符串
- ffmpeg - 如何在具有多个输入的硬件加速上使用 ffmpeg?
- laravel - 从控制器函数中获取特定值
- javascript - Javascript正则表达式选择没有特殊字符的单词
- javascript - jQuery 没有找到 Django 返回的“span”元素
- artifactory - 使用远程存储库升级 Artifactory 设置
- imagemagick - 无法使用 ImageMagick 限制内存使用量
- javascript - 如何禁用下拉菜单中的选项?
- python-3.x - Python:如何在跳过标题行的同时对 CSV 文件中的列求和