首页 > 解决方案 > 如何让所有游戏对象检查哪些游戏对象有碰撞器,哪些游戏对象根本没有碰撞器?

问题描述

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

像这样的东西。目标是找出哪些游戏对象有碰撞器,哪些游戏对象根本没有碰撞器。

标签: c#unity3d

解决方案


最简单的方法是获取对象上的所有对撞机,然后检查返回数组的长度,如果为 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组件并执行相同的操作。


推荐阅读