简体   繁体   中英

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. 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.

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:

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

YourClass is script with code from question.

If you use static variables in MonoBehaviour, theys basically need to be declared and initialized separately, and the initialization put into Awake() or Start(). Otherwise they will keep their old value when the MonoBehaviour is reinitialized on scene load, and you'll get issues when loading scenes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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