deyan
deyan

Reputation: 31

Scene not changing when the game is exported, even though it does in the engine

Using unity for a small video game, changing levels works in the engine completely fine, but when I export it to .exe it just doesn't work. The game itself works fine in .exe, only level changing doesn't work

public KeyCode nextLevelKey;

if(Input.GetKeyDown(nextLevelKey) && gameOver == true)
    {
        SceneManager.LoadScene(nextLevel.name);
        Debug.Log("loaded next level");
    }

Any ideas on why it doesn't work when exported? I have included every scene in the right order when making the build so it's not that.

Upvotes: 3

Views: 142

Answers (2)

deyan
deyan

Reputation: 31

Ok, so I figured it out. Instead of making the nextLevel variable an Object I made it a string, and then in the object (that the code for changing levels is attached to) I entered the level name.

Upvotes: 0

behzad.robot
behzad.robot

Reputation: 707

Ok so i took a look at unity answers and found this:

https://answers.unity.com/questions/139598/setting-variable-as-type-quotscenequot.html and also this:

https://answers.unity.com/questions/205742/adding-scene-to-build.html

Editor Way: What people have tried in 2nd link i guess is with custom editor scripts !That you can keep your Object nextLevel field also add string nextLevelName; And then using OnValidate() or some other Editor event you can set nextLevelName value whenever nextLevel 's value changes and use SceneManager.Load(nextLevelName) instead.

Kinda Easier Way : Try converting that field to string it's a pain to update scene names twice (or maybe more) but fixes things anyways. To Smooth things a bit you can try sth like this , though I'm not sure what you're trying to achieve with having nextLevel as variable but you can try:

SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex +1)

Or you can have a Scenes class that provides a way of dealing with your nextLevel problem. Maybe with tokens? Maybe sth else.

public class Scenes
{
    public static string[,] scenes = new string[,]{
        {"first_level", "scene-1-name"},
        {"level_2", "scene-2-name"},
        {"level_3", "factory-level"},
        {"level_4", "scene-4-name"},
        {"level_5", "jungle"},
    };
    public static string GetSceneNameByToken(string token)
    {
        for (var i = 0; i < scenes.GetLength(0); i++)
            if (scenes[i, 0] == token)
                return scenes[i, 1];
        return null;
    }
}

I Personally like the 2nd approach cos first one is still kinda unreliable imo (specially if you were to change unity version in middle of project or for next projects) maybe that's cos I've not worked with Editor Events much idk.

Upvotes: 1

Related Questions