简体   繁体   English

在Unity中使用场景名称获取级别索引

[英]Get level index by using scene name in Unity

I know that there is a way to get level name by index: 我知道有一种通过索引获取级别名称的方法:

string levelName = Application.GetLevelNameByIndex(2);

But is there a way to identify the level index of a scene using its name? 但是,有没有一种方法可以使用其名称来标识场景的级别索引?

Looks like that's not very well supported right now, see this answer . 看起来目前还没有很好的支持,请参见此答案

Only in editor - as per this question. 仅在编辑器中-根据此问题。

Vote for it here, it's a bizarrely absent feature. 在这里投票,这是一个奇怪的缺席功能。

Note that if you want to show text to the user, you probably want a long name, a description, and a screenshot anyway. 请注意,如果要向用户显示文本,则可能始终需要长名称,描述和屏幕截图。

EDIT: Found an answer that has an editor script that may be of assistance. 编辑: 找到了一个可能具有帮助的编辑器脚本的答案。

Here is a method you could use, assuming you know how many scenes are in your game. 假设您知道游戏中有多少个场景,可以使用以下方法。

using UnityEngine;
using System.Collections;

public class SceneDetector : MonoBehaviour {
    public int numberOfScenes = 5;
    public String[] sceneNames;

    void Start() {
        sceneNames = new String[numberOfScenes];
        for(int i = 0; i < numberOfScenes; i++)
        {
            sceneNames[i] = Application.GetLevelNameByIndex(i);
        }
    }

    public int GetSceneIndex(String sceneName)
    {
        for(int i = 0; i < sceneNames.length; i++)
        {
            if(sceneName == sceneNames[i])
            {
                return i;
            }
        }
        return -1;
    }
}

And of course as you can see if you run GetSceneIndex and it returns -1, then the string you passed in is not a name of a scene. 当然,如您所见,如果您运行GetSceneIndex并返回-1,则您传入的字符串不是场景名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM