复杂对象上的多个碰撞体

Multiple Colliders on Complex Object

我设计了一个复杂的城市,其中包含道路、侧面、建筑物、树木等数千个对象,并导入到 Unity3d

我想在它们上面放置碰撞体,这样当玩家击中它们时,它应该面对碰撞而不应该穿过它们

虽然它有很多物体,但如果我对每个物体都一个一个地对撞机,那将花费很多时间。有没有其他方法我可以 select 所有这些并放置对撞机。

此外,如果我select所有对象并放置对撞机(Mesh Collider)。它没有添加到对象

请帮忙

编辑器脚本 助您一臂之力。我会写一个类似于这个例子的工具。它使用 Menu Item,可以通过 Window -> Collider Tool 选择。然后它运行我们的自定义方法来查找我们想要添加对撞机的所有网格,然后添加一个并记录更改了哪些游戏对象。

using UnityEditor;
using UnityEngine;
using System.Collections.Generic;

public static class ColliderTool
{
    [MenuItem("Window/Collider Tool")]
    public static void RunTool()
    {
        List<MeshFilter> meshes = findObjectsThatNeedColliders();

        for (int i = 0; i < meshes.Count; i++) 
        {
            GameObject go = meshes[i].gameObject;

            // Add a collider to each mesh and record the undo step.
            MeshCollider collider = Undo.AddComponent<MeshCollider>(go);

            // Use the existing mesh as the collider mesh.
            collider.sharedMesh = meshes[i].sharedMesh;

            Debug.Log("Added a new collider on: " + go.name, go);
        }

        Debug.Log("Done");
    }

    private static List<MeshFilter> findObjectsThatNeedColliders()
    {
        // This list will be filled with all meshes, which require a collider.
        List<MeshFilter> meshesWithoutCollider = new List<MeshFilter>();

        // Get all meshes in the scene. This only returns active ones.
        // Maybe we also need inactive ones, which we can get via GetRootGameObjects and GetComponent.
        MeshFilter[] allMeshes = GameObject.FindObjectsOfType<MeshFilter>();

        foreach(MeshFilter mesh in allMeshes)
        {
            if(mesh.GetComponent<Collider>() == null)
                meshesWithoutCollider.Add(mesh);
        }

        return meshesWithoutCollider;
    }
}

您可能需要更复杂的规则来确定哪些对象需要碰撞器以及它应该是哪种类型,但是一个简单的工具仍然可以在手动调整所有内容之前为您节省大量时间。

您还应该考虑根据此选择。 Selection class 可以为您提供所有选定对象的列表。一些想法:

  • 将 MeshCollider 添加到所有选定对象(如果尚不存在)。
  • 将 BoxCollider 添加到选定对象,并根据 MeshRenderer 的变换大小或边界框将其缩放到近似大小。

我的解决方案是基于您关于如何为大型场景中的多个对象添加对撞机的问题。但是,这可能不是总体最佳解决方案。也许过多的 MeshCollider 会影响物理性能。您很可能希望用长方体和球体来近似大多数碰撞器,但当然您仍然可以编写一个工具来帮助您。