加载新场景后,变量值将被删除 [英] Variable values gets deleted after a new scene is loaded

查看:44
本文介绍了加载新场景后,变量值将被删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做的简短说明: 我正在Unity中进行项目.在第一个场景中,我有一个带有8个输入字段的UI画布,供用户键入最多8个名称.当用户输入完他/她想要的名称数量后,他/她按下完成"按钮,所有名称以正确的顺序添加到列表中,并加载新场景.然后游戏开始,然后游戏以慢性顺序浏览列表,并将任务交给轮到它的人.

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;
    }
}

当用户在UI输入字段中完成名称输入后,此代码由结束编辑"事件执行.当用户输入了他/她想要的名称时,他/她按下完成"按钮,并执行以下代码:

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.

感谢您的帮助.

推荐答案

加载场景时(如果不是附加方式),它将在加载新场景之前销毁所有内容.如果您不想自动销毁GameObject(及其属性),请使用以下命令: https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

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

这篇关于加载新场景后,变量值将被删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆