在 Unity 中,你可以使用 C# 脚本来实现批量给指定文件夹下的 prefab 资源挂载某个指定的 prefab。以下是一个示例脚本:

using UnityEngine;
using UnityEditor;
using System.IO;

public class BatchAttachPrefab : MonoBehaviour
{
    [MenuItem("Custom/AttachPrefabToFolder")]
    public static void AttachPrefabToFolder()
    {
        // 获取指定的 prefab
        GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Prefabs/YourPrefab.prefab");

        // 获取指定的文件夹路径
        string folderPath = "Assets/Your/Folder/Path";

        // 获取文件夹下的所有 prefab 资源路径
        string[] prefabPaths = Directory.GetFiles(folderPath, "*.prefab", SearchOption.AllDirectories);

        foreach (string prefabPath in prefabPaths)
        {
            // 加载 prefab 资源
            GameObject obj = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);

            // 实例化 prefab
            GameObject instance = PrefabUtility.InstantiatePrefab(prefab, obj.transform.parent) as GameObject;
            instance.transform.localPosition = obj.transform.localPosition;
            instance.transform.localRotation = obj.transform.localRotation;
            instance.transform.localScale = obj.transform.localScale;

            // 替换原有的 prefab 资源
            PrefabUtility.SaveAsPrefabAsset(instance, prefabPath);

            // 销毁实例
            DestroyImmediate(instance);
        }

        // 刷新 Unity 编辑器
        AssetDatabase.Refresh();
    }
}

使用方法:

  1. 将上述脚本保存为 BatchAttachPrefab.cs,然后将其放入 Unity 项目中的 Editor 文件夹下(如果不存在 Editor 文件夹,请手动创建)。
  2. 在 Unity 编辑器中,点击 Custom 菜单,然后选择 AttachPrefabToFolder
  3. 在弹出的窗口中,指定你要挂载的 prefab 和目标文件夹的路径。
  4. 点击确定后,脚本将会批量遍历目标文件夹下的所有 prefab 资源,并将指定的 prefab 挂载到每个 prefab 中。

请注意,这个脚本会修改 prefab 文件,所以在运行之前请确认你的资源已备份。另外,这个脚本只能在 Unity 编辑器中运行,不能在游戏运行时使用

unity 写一个脚本 批量给指定文件夹下的prefab资源挂载某个指定的prefab。要求直接生效到资源中。

原文地址: https://www.cveoy.top/t/topic/hZaM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录