Skip to content

Instantly share code, notes, and snippets.

@shiena
Last active December 15, 2023 06:14
Show Gist options
  • Save shiena/1c79fc1d1ad26274e41294809ad199b8 to your computer and use it in GitHub Desktop.
Save shiena/1c79fc1d1ad26274e41294809ad199b8 to your computer and use it in GitHub Desktop.
Unityでupm内にあるreadonlyなprefabのvariantを作るエディタ拡張
// Copyright 2022 KOGA Mitsuhiro Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
using System.IO;
using UnityEditor;
using UnityEngine;
public class PrefabVariantGenerator : EditorWindow
{
private GameObject _source;
[MenuItem("Tools/PrefabVariantGenerater")]
public static void Window()
{
GetWindow<PrefabVariantGenerator>($"{nameof(PrefabVariantGenerator)}");
}
public void OnGUI()
{
_source = EditorGUILayout.ObjectField("Source Prefab", _source, typeof(GameObject), false) as GameObject;
if (!_source)
{
EditorGUILayout.LabelField("Missing:", "Select an prefab first");
return;
}
if (!PrefabUtility.IsPartOfPrefabAsset(_source))
{
EditorGUILayout.LabelField("Failure:", $"{_source.name} is not prefab");
return;
}
var path = AssetDatabase.GetAssetPath(_source);
if (string.IsNullOrWhiteSpace(path))
{
return;
}
var baseName = Path.GetFileNameWithoutExtension(path);
if (GUILayout.Button($"Create Variant {baseName}"))
{
var requestPath = EditorUtility.SaveFilePanel(
$"Create Variant of {baseName}",
Application.dataPath,
$"{baseName}Variant.prefab",
"prefab");
if (!string.IsNullOrWhiteSpace(requestPath) && requestPath.StartsWith(Application.dataPath))
{
var leaf = new DirectoryInfo(Application.dataPath).Name;
var savePath = requestPath.Replace(Application.dataPath, leaf);
var successSave = false;
try
{
AssetDatabase.StartAssetEditing();
if (PrefabUtility.InstantiatePrefab(_source) is GameObject objSource)
{
PrefabUtility.SaveAsPrefabAssetAndConnect(objSource, savePath,
InteractionMode.UserAction, out successSave);
DestroyImmediate(objSource);
}
}
finally
{
AssetDatabase.StopAssetEditing();
}
if (successSave && File.Exists(savePath))
{
var savedAsset = AssetDatabase.LoadMainAssetAtPath(savePath);
if (savedAsset)
{
Selection.objects = new[] { savedAsset };
EditorGUIUtility.PingObject(savedAsset);
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment