场景里面有一些丢失的脚本,会造成游戏报警告,还是需要清理干净的
为了方便美术,写个小工具,刚开始还是被坑到了,遍历了所有的物体,
将所有的组件加入到数组里,判断如果组件为空的话删除,但是删不掉 也是醉了
搜索了好久发现了原因,需要先序列化物体,然后得到它的序列化属性,将对应
的属性根据索引删除掉。之后重新应用属性即可。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class deleNullComponent : EditorWindow {
[MenuItem("tool/deleComponent")]
static void window()
{
deleNullComponent win = (deleNullComponent)EditorWindow.GetWindow(typeof(deleNullComponent), false, "tool", false);
win.Show();
}
int dex = 0;
void OnGUI()
{
GUIStyle style1 = new GUIStyle();
style1.fontSize = 15;
style1.normal.textColor = new Color(0.7f, 0.7f, 0.7f);
EditorGUILayout.LabelField("▼删除场景中的空脚本", style1, GUILayout.Width(60));
EditorGUILayout.LabelField("已经删除了" + " " + dex + " " + "个空脚本", style1, GUILayout.Width(100));
dex = 0;
//删除场景中的空脚本
if (GUI.Button(new Rect(200, 10, 70, 25), "删除"))
{
spaceScrip();
}
}
void spaceScrip()
{
List<GameObject> sceneRoot = new List<GameObject>();
List<GameObject> obj = new List<GameObject>();
//得到场景的根节点
UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects(sceneRoot);
for (int i = 0; i < sceneRoot.Count; i++)
{
Transform[] a = sceneRoot[i].GetComponentsInChildren<Transform>();
for (int j = 0; j < a.Length; j++)
{
GameObject go = a[j].gameObject; //得到数组中的单个object
SerializedObject so = new SerializedObject(go); // 将object序列化
var soProperties = so.FindProperty("m_Component");//得到object的Component序列化数组
var components = go.GetComponents<Component>();//得到物体的component数组
int propertyIndex = 0;
foreach (var c in components)//遍历component数组
{
if (c == null)
{
soProperties.DeleteArrayElementAtIndex(propertyIndex);
dex++;
}
++propertyIndex;
}
so.ApplyModifiedProperties();//这句话好重要 开始没加上 怎么都不成功 坑死我了
}
}
//将场景设置为dert
if (dex > 0)
UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());
}
}
亲,如果您觉得本文不错,愿意给我一些动力的话,请用手机扫描二维码即可向我打赏
打赏