使用EditorScript创建预制体变体
如何使用友元进行Unity内部API访问的方法,可以看我在这个UnityToolchainsTrick中写的教程
我也非常推荐UnityToolchainsTrick
库,很多大佬分享了不少编辑器方面的知识
//Create: Icarus
//ヾ(•ω•`)o
//2022-03-14 01:31
//Unity.InternalAPIEngineBridge.024
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace CabinIcarus.EditorFrame.UnityBind
{
public static class PrefabUtilityHelp
{
/// <summary>
/// 创建预制体变体
/// UnityCsReference\Editor\Mono\ProjectWindow\ProjectWindowUtil.cs
/// </summary>
/// <param name="gameObjects"></param>
/// <returns></returns>
public static GameObject[] CreatePrefabVariants(params GameObject[] gameObjects)
{
if (gameObjects == null)
return null;
foreach (var go in gameObjects)
{
if (go == null || !EditorUtility.IsPersistent(go))
return null;
}
var createdVariants = new List<GameObject>();
foreach (var go in gameObjects)
{
string sourcePath = AssetDatabase.GetAssetPath(go);
string sourceDir = Path.GetDirectoryName(sourcePath).Replace('\\', '/');
string variantPath = GetPrefabVariantPath(sourceDir, go.name);
variantPath = AssetDatabase.GenerateUniqueAssetPath(variantPath);
var variant = PrefabUtilityHelp.CreateVariant(go, variantPath);
if (variant != null)
createdVariants.Add(variant);
}
if (createdVariants.Count > 0)
{
Selection.objects = createdVariants.ToArray();
ProjectWindowUtil.FrameObjectInProjectWindow(createdVariants.Last().GetInstanceID());
}
return createdVariants.ToArray();
}
static string GetPrefabVariantPath(string folder, string gameObjectName)
{
return string.Format("{0}/{1} Variant.prefab", folder, gameObjectName);
}
public static GameObject CreateVariant(GameObject assetRoot, string path)
{
return PrefabUtility.CreateVariant(assetRoot, path);
}
}
}
晒一下目前工具的样子,哈哈
生成的结果