每次调用 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
}
}
}
最佳答案
levelname
是实例属性。 NextLevel
类的每个实例都有自己的 this 值。因此,如果您每次创建 NextLevel
的新实例并调用 Update
,计数总是从 1 开始。
您可以将 levelname
切换为静态属性或始终使用类 NextLevel
的一个实例。
关于c# -++ 运算符的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39304967/