Jens Jens - 21 days ago 6
C# Question

Variable values gets deleted after a new scene is loaded (C#) (Unity)

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.

Answer

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