简体   繁体   English

为什么我的Unity C#脚本中的变量重置为0

[英]Why does my variable reset to 0 in my Unity C# script

I have a simple project with a button in a scene that, when tapped, starts the StartWorking function in this script: 我有一个简单的项目,在场景中有一个按钮,点击该按钮后,将在此脚本中启动StartWorking函数:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class DoWork : MonoBehaviour {

  public int Cash = 5;

  public void StartWorking() {
        Debug.Log (Cash);
        Debug.Log ("Ran!");
        Cash++;
        Debug.Log (Cash);
  }
}

When ran and on tapping the button the console says: 当运行并点击按钮时,控制台会显示:

0 0
Ran! an!
1 1个

instead of expected: 而不是预期的:

5 5
Ran! an!
6 6

Any idea why the variable is not keeping it's set initial value in the class? 知道为什么变量不能在类中保留其初始值吗?

Thanks. 谢谢。

When a variable is public, the value on the script does not matter. 当变量是公共变量时,脚本上的值无关紧要。 You probably have it as 0 in Inspector and this is the value used at runtime. 您可能在Inspector中将其设置为0,这是运行时使用的值。 If you want the value of the script to be used, you need to click the component setting wheel and Reset component. 如果要使用脚本的值,则需要单击组件设置轮,然后单击“重置组件”。

If you have to see the value but want to use the script value, make it private and click the little down arrow next to the lock on top of the inspector. 如果必须查看该值但要使用脚本值,请将其设为私有,然后单击检查器顶部的锁旁边的小向下箭头。 This will display private member as well. 这也将显示私人成员。 You won't be able to change them though via inspector, just look. 通过外观检查器,您将无法更改它们,请看一下。

Cash variable is public and I think you change the value of Cash in inspector . Cash变量是公共的,我认为您会更改inspectorCash的值。

Once you change the value of a variable in inspector, unity will ignore the initial value in code and replace it with value in inspector. 一旦您在检查器中更改了变量的值,Unity将忽略代码中的初始值,并将其替换为检查器中的值。

Try to change public int Cash = 5; 尝试将public int Cash = 5;更改public int Cash = 5; to private int Cash = 5; private int Cash = 5; and you will get the result you want 你会得到你想要的结果

Is your script linked to an object in the scene ? 您的脚本是否链接到场景中的对象? If it's the case, the "cash" variable can be edited in the inspector and overwrite the initialisation in your script. 在这种情况下,可以在检查器中编辑“ cash”变量,并覆盖脚本中的初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM