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

实现效果

效果展示

代码

1、SceneDrawer.cs

using UnityEngine.SceneManagement;
using UnityEditor;
using UnityEngine;

public class SceneAttribute : PropertyAttribute {
    
     }

[CustomPropertyDrawer(typeof(SceneAttribute))]
public class SceneDrawer : PropertyDrawer
{
    
    
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
    
    
        EditorGUI.BeginProperty(position, label, property);

        var sceneName = property.stringValue;
        var sceneIndex = -1;

        var sceneNames = new string[SceneManager.sceneCount];
        for (var i = 0; i < SceneManager.sceneCount; i++)
        {
    
    
            var scene = SceneManager.GetSceneAt(i);
            sceneNames[i] = scene.name;
            if (sceneName == scene.name)
                sceneIndex = i;
        }

        var newSceneIndex = EditorGUI.Popup(position, label.text, sceneIndex, sceneNames);
        if (newSceneIndex >= 0)
            property.stringValue = sceneNames[newSceneIndex];

        EditorGUI.EndProperty();
    }
}

2、Teleport.cs

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

public class Teleport : MonoBehaviour
{
    
    
    [Scene]
    public string currentSceneName;  //当前场景名
    [Scene]
    public string toGoSceneName;  //要去的场景名
}

猜你喜欢

转载自blog.csdn.net/qq_44887198/article/details/129240537