简体   繁体   English

加载场景统一时将静态变量重置为零

[英]Reseting a static variable back to zero when loading a scene unity

I have a problem i have to use static variable because if i don't use it if i use normal variable italways prints (on point where i debug.log) 1 even if i click on gameobject 3 times.我有一个问题,我必须使用静态变量,因为如果我不使用它,如果我使用普通变量,即使我单击游戏对象 3 次,它也会打印(在我 debug.log 的位置)1。 it works but when i reload/load a new scene a scene variable stays the same for instance 2 but i need it to be 0. Basically it works fine i just have to reset variable after loading current scene aggain.它可以工作,但是当我重新加载/加载新场景时,场景变量保持不变,例如 2,但我需要它为 0。基本上它工作正常,我只需要在再次加载当前场景后重置变量。

public static int end;

    void OnMouseDown(){
        end +=1;
        Debug.Log (end);
        if (end == 1)  {
            Vector2 pos1 = new Vector2 (-6,0);
            Instantiate (Redstar,pos1,Quaternion.identity);
        }
        else if ( end == 2 ) {
            Vector2 pos2 = new Vector2 (-5,0);
            Instantiate (Redstar, pos2,Quaternion.identity);
        }
        else if ( end ==3 ) {
            Vector2 pos3 = new Vector2 (-4,0);
            Instantiate (Redstar, pos3,Quaternion.identity);
            GameObject.Find ("ballon").SendMessage ("Finnish");
        }



    }

Add an empty GameObject to scene and add script with this code to it:向场景中添加一个空的 GameObject 并向其添加包含以下代码的脚本:

void Start(){
    YourClass.end = 0;
}

YourClass is script with code from question. YourClass 是带有问题代码的脚本。

If you use static variables in MonoBehaviour, theys basically need to be declared and initialized separately, and the initialization put into Awake() or Start().如果在 MonoBehaviour 中使用静态变量,基本上需要分别声明和初始化,初始化放到 Awake() 或 Start() 中。 Otherwise they will keep their old value when the MonoBehaviour is reinitialized on scene load, and you'll get issues when loading scenes.否则,当 MonoBehaviour 在场景加载时重新初始化时,它们将保留其旧值,并且在加载场景时会出现问题。

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

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