Jens
Jens

Reputation: 47

Variable values gets deleted after a new scene is loaded

Short explenation, of what I'm trying to do: I'm working on a project in Unity. In the first scene I have a UI canvas with 8 Input Fields, for the user to type in up to 8 names. When the user is done typing in the amount of names he/she wants, he/she presses a 'done' button, and all of the names are added in correct order to a list and a new scene is loaded. Then the game begins, and the game goes through the list in chronic order, and gives tasks to the person whos turn it is.

The problem: The names are added correctly to the list. But when the scene changes, the list empties itself, and all the string variables are deleted. I can't figure out why.

public string namePlayer1, namePlayer2, namePlayer3;
public bool player1IsPlaying, player2IsPlaying, player3IsPlaying = false;
List<string> playerList;

public void getInput1(string player1Name)
{
   if (player1Name == "")
    {
        player1IsPlaying = false;
    }
    else
    {
        namePlayer1 = player1Name;
        player1IsPlaying = true;
    }
}

This code is executed by an 'on end edit' event, when the user has finished typing in a name in the UI Input Field. When the user has typed in the names he/she wants, he/she presses the 'done' button, and this code is executed:

public void PutNamesInList()
{
    if (player1IsPlaying)
    {
        playerList.Add(namePlayer1);
    }
    if (player2IsPlaying)
    {
        playerList.Add(namePlayer2);
    }
    if (player3IsPlaying)
    {
        playerList.Add(namePlayer3);
    }
    startGame();
}

Now when a new scene is loaded, all the variables are empty.

Any help is appreciated.

Upvotes: 0

Views: 209

Answers (2)

Muhammad Faizan Khan
Muhammad Faizan Khan

Reputation: 10551

If you are not willing to use Object.DontDestroyOnLoad You can also use PlayerPrefs which means

Stores and accesses player preferences between game sessions.

Upvotes: -1

Rich Joslin
Rich Joslin

Reputation: 204

When loading a scene (if not in an additive way) it will destroy everything before loading the new scene. If you don't want a GameObject (and its properties) to be destroyed automatically, use this: https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

Upvotes: 2

Related Questions