How to send final game score between Cocos Creator scenes?

377 Views Asked by At

I'm trying to create a game with Cocos Creator. I'm using more than one file in the game. Like Game.js GameOver.js Jump.js etc. I'm collecting scores with GainScore.js. I have to send final score to GameOver.js file. I show the score properly during the game. But when the game is over I have to send it to the other screen. How can I use the game score as global?

My gainScore function:

  gainScore() {
    this.score += 1;
    if (this.scoreDisplay === null) return;
    this.scoreDisplay.string = this.score;
  },

My GameOver.js file

cc.Class({
    extends: cc.Component,

    properties: {
        scoreEnd: {
            default: null,
            type: cc.Label,
        },
    },

    start() {
        this.scoreEnd.string = this.score.toString(); // I can't access with this way
    },
});
1

There are 1 best solutions below

0
doğukan On BEST ANSWER

You can use CommonJS. Create a new file called Global.js.

scripts
  |__ GameOver.js
  |__ GainScore.js
  |__ Global.js

and keep your global variables here.

Global.js:

module.exports = {
    score: 0
};

And use with require in other files:

let Globals = require("Globals");

....

gainScore() {
   Globals.score += 1; // not this.score, should be Globals.score
   if (this.scoreDisplay === null) return;
   this.scoreDisplay.string = Globals.score;
},

You should require all other files that will use

let Globals = require("Globals");

cc.Class({
    extends: cc.Component,

    properties: {
        scoreEnd: {
            default: null,
            type: cc.Label,
        },
    },

    start() {
        this.scoreEnd.string = Globals.score.toString();
    },
});