简体   繁体   中英

How do I get a Unity scene name when they are stored as an array of Objects

I have a list of Objects. They are Unity scenes.

public Object[] scenes;

I would like to fill this array with unity scenes, as a convenient way of storing the sequential order they should load within Unity's inspector.

I attempted to use the SceneManager to load a level using a reference to this array

public int currentSceneNumber = 0;
public void LoadNext()
{
    if (scenes.Length >= currentSceneNumber + 1)
    {
        currentSceneNumber += 1;
        SceneManager.LoadScene(scenes[currentSceneNumber].ToString());
    }
    else
    {
        Debug.Log("Level.cs: Unable to load next level.");
        return;
    }
}

But turning the scene into a string results in 'scenename(UnityEngine.SceneAsset)' The (login (UnityEngine.SceneAsset) is the problem part. It will result in the following error

Scene 'prototype02_Scene (UnityEngine.SceneAsset)' couldn't be loaded because it has not been added to the build settings or the AssetBundle has not been loaded.
To add a scene to the build settings use the menu File->Build Settings...

How do I get the scene name as a string from the scene object in my array?

You can't do this outside the Editor.

When you use public UnityEngine.Object[] scenes; to hold the Scenes, Unity will use SceneAsset as the placeholder to hold those scenes.

The problem with this is that SceneAsset is from the UnityEditor namespace which means that your code will only work in the Editor with the the AssetDatabase . You can't build it to run on any standalone platform. You will get this error if you attempt to build your project.

This is how to get all the scenes and store them in an array(Should work in the Editor and build):

public Scene[] scenes;

...


void initScenes()
{   
    int sceneCount = SceneManager.sceneCountInBuildSettings;
    scenes = new Scene[sceneCount];
    for (int i = 0; i < sceneCount; i++)
    {
        scenes[i] = SceneManager.GetSceneByBuildIndex(sceneCount);
    }
}

Your loading code:

SceneManager.LoadScene(scenes[currentSceneNumber].name);

If you are sure that this is an Editor plugin and not something you need to build or run outside the Editor then here is your answer:

First of all, you are using the Object name which has nothing to do with the scene name since Object.ToString() is an override function that retrieves the name of the Object.

Just cast the Object array to SceneAsset then access the name of the scene from that instead of the name of the Object like you are currently doing.

SceneManager.LoadScene(((SceneAsset)scenes[currentSceneNumber]).name);

or

SceneAsset scene = scenes[currentSceneNumber] as SceneAsset;
SceneManager.LoadScene(scene.name);

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