AddPrefabTool
介绍
批量向指定物体添加子物体
使用场景
假设有10个动物,需要给所有动物添加一个球作为子物体
工具原理
- OGUI绘制Windows窗口
EditorGUILayout.TextField("Title", _filePath)
(GameObject)EditorGUILayout.ObjectField("Title", _prefab, typeof(GameObject), true);
- AssetDatabase处理编辑器下资源操作
//获取预制体
string[] guids = AssetDatabase.FindAssets("t:Prefab", new[] { _filePath });
foreach (string guid in guids)
{string assetPath = AssetDatabase.GUIDToAssetPath(guid);GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(assetPath);
}
- PrefabUtility对预制体进行操作
// 打开预制体进行编辑
GameObject prefabInstance = PrefabUtility.LoadPrefabContents(assetPath);// 实例化预制体
GameObject instantiate = PrefabUtility.InstantiatePrefab(_prefab) as GameObject;// 保存对预制体的修改
PrefabUtility.SaveAsPrefabAsset(prefabInstance, assetPath);// 卸载预制体内容
PrefabUtility.UnloadPrefabContents(prefabInstance);
- AssetDatabase 刷新资产数据
AssetDatabase.Refresh();
代码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;public class AddPrefabTool : EditorWindow
{private string _filePath = "YourFilePath";private string _parent = "YourParent";private GameObject _prefab;[MenuItem("Tools/AddPrefabTool")]public static void ShowWindow(){GetWindow<AddPrefabTool>();}private void OnGUI(){GUILayout.Label("批量向模型添加内容", EditorStyles.boldLabel);_filePath = EditorGUILayout.TextField("被添加的物体路径", _filePath);_parent = EditorGUILayout.TextField("被添加的物体父物体名字", _parent);_prefab = (GameObject)EditorGUILayout.ObjectField("添加的物体", _prefab, typeof(GameObject), true);if (GUILayout.Button("添加")){AddPrefab();}}private void AddPrefab(){// 查找指定文件夹中的所有预制体string[] guids = AssetDatabase.FindAssets("t:Prefab", new[] { _filePath });foreach (string guid in guids){string assetPath = AssetDatabase.GUIDToAssetPath(guid);GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(assetPath);if (prefab != null){// 打开预制体进行编辑GameObject prefabInstance = PrefabUtility.LoadPrefabContents(assetPath);// 查找预制体中的 _parent子物体Transform modelTransform = string.IsNullOrEmpty(_parent)? prefabInstance.transform: prefabInstance.transform.Find(_parent);if (modelTransform == null){Debug.LogError($"No 'Model' child found in prefab at {assetPath}");PrefabUtility.UnloadPrefabContents(prefabInstance);continue;}// 检查是否已经存在名为 _prefab 的子物体,避免重复添加if (modelTransform.Find(_prefab.name) == null){// 实例化 _prefab 预制体并将其作为 _parent 的子物体GameObject instantiate = PrefabUtility.InstantiatePrefab(_prefab) as GameObject;if (instantiate != null){instantiate.transform.SetParent(modelTransform, false);instantiate.name = _prefab.name;}// 保存对预制体的修改PrefabUtility.SaveAsPrefabAsset(prefabInstance, assetPath);}else{Debug.LogWarning($"'Shadow' already exists in prefab at {assetPath}");}// 卸载预制体内容PrefabUtility.UnloadPrefabContents(prefabInstance);}}// 刷新资产数据库AssetDatabase.Refresh();}
}