简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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