How to use globale variables

Hi guys,
i have a problem to pass some variables to scene in another. The easy step i think is by global variables but i don’t no how it works at all. And in google i don’t see nothing interesting…
Help please :slight_smile:

I have found this :slight_smile:in the first scene :

cc.sys.localStorage.setItem(‘myScore’, this.gameScore);

and in other :

gameScore = cc.sys.localStorage.getItem(‘myScore’);

updateScore(){
    this.getComponent(cc.Label).string = 'test : ' + this.gameScore.toString();
}

I think i am close but actually it does not work :frowning:

It’s good, i have finally find what’s going on !
script in the scene 1 :

addScore(){
    this.gameScore ++;
    this.scoreLabel.string = 'Score : ' + this.gameScore.toString();
    cc.sys.localStorage.setItem('myScore', JSON.stringify(this.gameScore));
}

and in th scene2 :

start(){

    this.scoreLabel.string = JSON.parse(cc.sys.localStorage.getItem('myScore'));
}

Hope that will be useful for some peoples.

Hi @flyingbibi
I’ve recorded a video tutorial to demonstrate usage of global variables here is it:

Hope it helps :wink:

2 Likes

Why didn’t work?

hi
I can’t help replying this question. hahaha.
the simplest way to pass some variables from one scene to another is below:

cc.vv = {};
cc.vv.myVar1 = 'value';
cc.vv.myVar2 = 'value';

in fact. you can put any vars in cc.vv;
don’t ask me why cc.vv, i can only tell you: it’s a long story. hahahaha.


sorry,I’m kidding.
if you don’t want to use cc.vv, you can also use cc.xx,cc.oo whatever you want.

furthermore,if you are really hate to use cc, you can also put your global vars to window object. see the example below:

window.xx = {};
xx.myVar1 = '';
xx.myVar2 ='';

then,you can call xx anywhere in your code.


you are lucky, if you are using TypeScript as your programming language. there is an awesome solution for your question.

//MyGlobal.ts
export class MyGlobal{
public static myVar1:string = 'i am string var';
public static myVar2:number = 0;
}

//in another ts
import {MyGlobal} from './MyGlobal'
...
//call it like this
let myVar1 = MyGlobal.myVar1;
let myVar2 = MyGlobal.myVar2;

good luck,guy.we will meet again.

1 Like

Don’t use local storage as it’s slower than memory. unless you wanted to persist data on next load.

Use like this.

// global.js
module.exports = {
    speed: 100,
    life: 20
};
// in another file
const Global = require("global");

// then you can get variables/attributes defined in global object. eg:
let myLife = Global.life;

// you can updated them as well.
Global.life = Global.life - damangeAmount;

// or add new variable
Global.iAmNew = "Cool";

1 Like