Unity如何为场景切换脚本制作Inspector下拉选择器?
实现Inspector场景下拉选择的LevelSwap脚本修改方案
方法1:使用SceneAsset直接引用(推荐)
这种方式支持在Inspector里直接拖拽或下拉选择场景,避免手动输入字符串出错,同时通过条件编译处理编辑器与运行时的差异,打包时不会产生冗余代码。
修改后的完整代码:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; #if UNITY_EDITOR using UnityEditor; #endif public class LevelSwap : MonoBehaviour { #if UNITY_EDITOR [SerializeField] private SceneAsset targetScene; #endif [SerializeField] private string levelToLoad = "Stage2"; private void OnValidate() { #if UNITY_EDITOR // 编辑器内自动同步SceneAsset引用到场景名字符串 if (targetScene != null) { levelToLoad = targetScene.name; } #endif } private void OnTriggerEnter(Collider other) { if (other.CompareTag("Player") && !string.IsNullOrEmpty(levelToLoad)) { SceneManager.LoadScene(levelToLoad); } } }
方法2:自定义属性实现场景下拉菜单
如果偏好直接对字符串字段做下拉扩展,可以通过自定义属性绘制器实现:
1. 创建自定义属性类
using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif public class SceneDropdownAttribute : PropertyAttribute { } #if UNITY_EDITOR [CustomPropertyDrawer(typeof(SceneDropdownAttribute))] public class SceneDropdownDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { if (property.propertyType != SerializedPropertyType.String) { EditorGUI.HelpBox(position, "SceneDropdown仅支持字符串类型字段", MessageType.Error); return; } // 获取Build Settings中已添加的所有场景 var buildScenes = EditorBuildSettings.scenes; string[] sceneNames = new string[buildScenes.Length]; int selectedIndex = 0; for (int i = 0; i < buildScenes.Length; i++) { sceneNames[i] = System.IO.Path.GetFileNameWithoutExtension(buildScenes[i].path); if (sceneNames[i] == property.stringValue) { selectedIndex = i; } } // 绘制下拉选择菜单 selectedIndex = EditorGUI.Popup(position, label, selectedIndex, sceneNames); property.stringValue = sceneNames[selectedIndex]; } } #endif
2. 修改LevelSwap脚本
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class LevelSwap : MonoBehaviour { [SceneDropdown] public string levelToLoad = "Stage2"; private void OnTriggerEnter(Collider other) { if (other.CompareTag("Player")) { SceneManager.LoadScene(levelToLoad); } } }
关键注意事项
- 无论使用哪种方法,需要加载的场景必须添加到Build Settings的「Scenes In Build」列表中,否则下拉菜单不会显示该场景,运行时也无法正常加载。
内容的提问来源于stack exchange,提问作者Daniel Budgieton
相关产品推荐
相关产品推荐

