在实际做项目中,有时候经常需要对地形的碰撞体进行编辑,比如很多不需要加碰撞体的对象却带着碰撞体,如果手动去移除,工作量又是很大(经常子物体又是套着子物体,十分复杂),有时候又需要添加碰撞体,本人就移除碰撞体这件事件花了很长时间,不胜其烦,网上的资料也不是太多,也不全。所以在这给大家贴出流程与代码。可以使开发更加方便。
- 新建一个名为Editor的文件夹,在这个文件夹下新建一个脚本EditorTest
- 打开脚本,引入using UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class EditorTest : MonoBehaviour
{
[MenuItem("AddRemoveCompentEditor/RemoveCompent")]
public static void RemoveCompent()
{
GameObject[] goArray = GameObject.FindGameObjectsWithTag("Test");
foreach (var item in goArray)
{
RemoveTest(item);
}
Debug.Log("移除成功");
}
[MenuItem("AddRemoveCompentEditor/AddCompent")]
public static void AddCompent()
{
GameObject[] goArray = GameObject.FindGameObjectsWithTag("Test");
foreach (var item in goArray)
{
AddTest(item);
}
Debug.Log("添加成功");
}
static void RemoveTest(GameObject go)
{
if (go.GetComponent<Collider>() != null)
{
foreach (var item in go.GetComponents<Collider>())
{
DestroyImmediate(item);
}
}
for (int i = 0; i < go.transform.childCount; i++)
{
RemoveTest(go.transform.GetChild(i).gameObject);
}
}
static void AddTest(GameObject go)
{
if (go.GetComponent<Collider>() == null)
{
go.AddComponent<BoxCollider>();
}
for (int i = 0; i < go.transform.childCount; i++)
{
AddTest(go.transform.GetChild(i).gameObject);
}
}
}