【问题标题】:Issue with ++ operator++ 运算符的问题
【发布时间】: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


【解决方案1】:

levelname 是一个实例属性。 NextLevel 类的每个实例都有自己的 this 值。因此,如果您每次创建 NextLevel 的新实例并调用 Update 计数总是从 1 开始。

您可以将levelname 切换为静态属性或始终使用NextLevel 类的一个实例。

【讨论】:

  • 我解决了这个问题,但只是为了将来,我将如何只使用 NextLevel 的一个实例?
  • @user3103529 我不知道你是如何创建和使用对象类型NextLevel,示例代码太少。但是在静态成员和实例成员之间阅读diferences,使用静态成员有一些后果,例如。如果您想要多个类静态成员的实例,每个实例始终具有相同的值..
【解决方案2】:

使用public static int levelname = 1; 而不是int levelname=1

【讨论】:

  • 而不是感谢支持答案,这将有助于其他人
  • 作为一般规则,您真的不应该在工程软件中使用静态或全局变量。随着时间的推移,试着培养你的基本软件工程技能!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-24
  • 2015-07-25
  • 1970-01-01
  • 1970-01-01
  • 2011-03-21
  • 2011-10-20
  • 1970-01-01
相关资源
最近更新 更多