Unity实现在Inspector面板中选择BuildSettings中已有的场景

该代码示例展示了如何在Unity编辑器中创建一个自定义的PropertyDrawer,用于SceneNameAttribute。这个drawer允许用户在Unity的Inspector面板中通过Popup选择场景名称,简化了在脚本中指定和切换场景的过程。
摘要由CSDN通过智能技术生成

实现效果

效果展示

代码

1、SceneNameDrawer.cs

using UnityEngine;
using UnityEditor;
using System.Linq;

public class SceneNameAttribute : PropertyAttribute { }

#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(SceneNameAttribute))]
public class SceneNameDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        // Get the list of scenes in Build Settings
        var scenes = EditorBuildSettings.scenes
            .Where(s => !string.IsNullOrEmpty(s.path))
            .Select(s => System.IO.Path.GetFileNameWithoutExtension(s.path))
            .ToArray();

        // Get the index of the currently selected scene
        var index = Mathf.Max(0, System.Array.IndexOf(scenes, property.stringValue));

        // Draw a popup to select the scene
        EditorGUI.BeginChangeCheck();
        index = EditorGUI.Popup(position, label.text, index, scenes);
        if (EditorGUI.EndChangeCheck())
        {
            property.stringValue = scenes[index];
        }
    }
}
#endif

2、Teleport.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Teleport : MonoBehaviour
{
    [SceneName]
    public string currentSceneName;  //当前场景名
    [SceneName]
    public string toGoSceneName;  //要去的场景名
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值