Unity EditorWindow 加载 Prefab 示例教程
要在 Unity EditorWindow 上加载 Prefab,您可以使用 EditorGUILayout.ObjectField 函数来创建一个可交互的对象字段,然后在 EditorWindow 的 OnGUI 函数中使用该函数来加载 Prefab。下面是一个示例代码:
using UnityEngine;
using UnityEditor;
public class MyEditorWindow : EditorWindow
{
private GameObject prefab;
[MenuItem("Window/My Editor Window")]
public static void ShowWindow()
{
EditorWindow.GetWindow(typeof(MyEditorWindow));
}
private void OnGUI()
{
// 创建一个可交互的对象字段,用于加载 prefab
prefab = EditorGUILayout.ObjectField('Prefab', prefab, typeof(GameObject), true) as GameObject;
if (GUILayout.Button("Instantiate"))
{
// 点击按钮后实例化 prefab
GameObject instance = Instantiate(prefab);
// 将实例化的 prefab 添加到场景中
SceneView sceneView = SceneView.lastActiveSceneView;
if (sceneView != null)
{
GameObjectUtility.SetParentAndAlign(instance, sceneView.camera.gameObject);
Undo.RegisterCreatedObjectUndo(instance, "Instantiate Prefab");
}
}
}
}
请确保将上述代码保存为 .cs 文件,并将其放置在 Unity 项目的 Editor 文件夹中。然后,您可以通过选择“Window”菜单并选择“My Editor Window”来打开自定义的 EditorWindow。在 EditorWindow 上,您将看到一个可交互的对象字段,您可以使用它来加载 Prefab。点击“Instantiate”按钮后,将实例化 Prefab 并将其添加到场景中。
原文地址: https://www.cveoy.top/t/topic/qBfn 著作权归作者所有。请勿转载和采集!