【发布时间】:2016-09-03 08:41:17
【问题描述】:
每次调用 LevelChange 函数时,我都会尝试将 1 添加到变量 levelname。但是,每次调用它时,它都会将值重置为 1,就像它最初在代码开头设置的那样。我习惯了 c++ 并且很困惑。这段代码有点草率,因为我尝试了很多方法来解决这个问题。任何帮助,将不胜感激。 缺少一个括号,因为由于某种原因我无法将此行放入代码块中。
public class NextLevel : MonoBehaviour {
int levelname = 1;
int newlevelname;
string levelnameS;
void LevelChange()
{
levelname++;
newlevelname = levelname;
string levelnameS = newlevelname.ToString(); //Converts newlevelname which is an int value to a string
Debug.Log(levelnameS); //prints to the console
SceneManager.LoadScene(levelnameS); //changes scene based on the level name. In this case its a number because thats what the levels are named.
Debug.Log(levelname);
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Return))
{
LevelChange(); //calls the level change function
}
}
}
【问题讨论】:
-
这个类的实例保存在哪里?
-
@VisualVincent 它是事件处理程序对象的一个组件。它在从一个级别切换到另一个级别时起作用,但是该值不会超过一次。这是否回答你的问题?我不确定你在问什么。
-
那么你的问题很可能是每次上新的关卡都会创建一个新的实例。接受其他人的建议并制作变量
static。 -
@VisualVincent 谢谢老兄!
-
没问题。您可以在MSDN Documentation 上阅读有关
static的更多信息。
标签: c# unity3d syntax logic operators