前言
有时会有对所有Prefab预制体进行统一修改的需求,比如修改组件脚本参数等。但是一个一个去修改的话数量少还好,数量多的话既没有效率又容易出错。本篇博客就是教大家如何一键修改所有预制体。
代码
话不多说,直接上干货。记得此脚本要放到Editor文件夹下。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.Linq;
using UnityEditor;
using UnityEngine;
[CreateAssetMenu(menuName = "Helper")]
public class MyHelper : ScriptableObject
{
[CustomEditor(typeof(MyHelper))]
public class Helper : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
if (GUILayout.Button("开始"))
{
//找到所有Project下GameObject
string[] guids = AssetDatabase.FindAssets(string.Format("t:{0}", "GameObject"));
//对每个GameObject进行操作
for (int i = 0; i < guids.Length; i++)
{
//转化路径
string assetPath = AssetDatabase.GUIDToAssetPath(guids[i]);
//加载对象
GameObject root = AssetDatabase.LoadAssetAtPath<GameObject>(assetPath);
//在这里进行操作,我这里示范的是对Prefab上所有的DeleteItemAction脚本进行操作
//如果每个Prefab上只有一个脚本的话GetComponents可以改成GetComponent,SelectMany换成Select
foreach (var go in root.DescendantsAndSelf()
.Where(n => n.GetComponent<DeleteItemAction>()).SelectMany(n => n.GetComponents<DeleteItemAction>()))
{
Debug.Log("-----------" + go.name);
}
//在这里储存预制体修改,用try catch是因为有可能有部分prefab会报错,但是并不影响操作
try
{
PrefabUtility.SavePrefabAsset(root);
}
catch (Exception e)
{
Debug.LogWarning(e.Message);
}
}
}
}
}
}
DescendantsAndSelf()
会报错,需要下载UnityStore免费的插件。
也可以自己实现,就是获取自身和所有子物体。
使用方法
点击Project中的Create选择Helper,或者在Project面板下右键->Create->Helper,会创建出一个ScriptableObject
,选中后在Inspector面板
点击开始就可以了,不需要处于运行模式下。
希望这篇博客能够帮到您。