首先,创建一个空物体(GameObject > Create Empty),命名为GameManager,接着添加脚本,代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//获取需要添加碰撞体的父物体
GameObject parentObject = GameObject.Find("ParentObject");
//遍历该父物体下的所有子物体,并为每个子物体添加碰撞体
foreach (Transform child in parentObject.transform)
{
child.gameObject.AddComponent<BoxCollider>();
}
}
// Update is called once per frame
void Update()
{
}
}
上面的代码使用了 BoxCollider 碰撞体,小伙伴们可以根据需要替换为其他类型的碰撞体,例如 SphereCollider、CapsuleCollider 等。