Editor下,通过PrefabStage监听打开/关闭Prefab编辑场景事件,通过PrefabStageUtility获取当前正在编辑的Prefab
using UnityEngine;
using UnityEditor;
using UnityEditor.Experimental.SceneManagement;
public class LevelPrefabSceneExtension
{
[InitializeOnLoadMethod]
public static void Init()
{
//打开Prefab事件
PrefabStage.prefabStageOpened += OnPrefabStageOpened;
//关闭Prefab事件
PrefabStage.prefabStageClosing += OnPrefabStageClosing;
}
private static void OnPrefabStageOpened(PrefabStage prefabStage)
{
//if(prefabStage.prefabAssetPath.StartsWith("Assets/···"))
if(prefabStage.prefabAssetPath.EndsWith("Cube.prefab"))
{
//在场景视图绘制按钮
SceneView.duringSceneGui -= DuringSceneGui;
SceneView.duringSceneGui += DuringSceneGui;
}
}
private static void OnPrefabStageClosing(PrefabStage prefabStage)
{
SceneView.duringSceneGui -= DuringSceneGui;
}
private static Rect buttonRect = new Rect(5,50,125,20);
private static void DuringSceneGui(SceneView sceneView)
{
Handles.BeginGUI();
if(GUI.Button(buttonRect,"仅在打开Cube时显示按钮",GUI.skin.box))
{
CheckPrefab();
}
Handles.EndGUI();
}
private static void CheckPrefab()
{
//获取当前打开的Prefab
PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if(prefabStage == null)
return;
GameObject prefabRoot = prefabStage.prefabContentsRoot;
if(prefabRoot == null)
return;
Debug.Log(prefabRoot);
}
}