How to use type script singleton?

How to use type script singleton?
0.0 0

#1

i cant do cocos creator javascript singleton,

but i dont now typescript ㅜㅜ

please help me


#2

Your question was not clear, it is Javascript or Typescript? Anyway, I will give the answer to Javascript, because it also works in Typescript.

Please, refer to http://docs.cocos.com/creator/manual/en/scripting/access-node-component.html#access-by-using-global-variable

You can declare the global variable in any script, just make sure it gets executed.

window.myGlobalVariable = 10;

Then you can acess it from anywhere

cc.log(myGlobalVariable);

#3

In JavaScript you can use statics instance, for example this GameMaster class:

var GameMaster = cc.Class({
extends: cc.Component,

properties: () => ({
    
}),

statics: {
    instance: null,
},

onLoad: function() {
    GameMaster.instance = this;
}

You can access GameMaster.instance from anywhere by require it beforehand.


#4

thanks for answer but…

i did javascript

DataManager.js


var DataManager = cc.Class({
extends: cc.Component,

properties: {
   name:'',
},

statics: {
    instance: null,
},

});

DataManager.instance = new DataManager();
module.exports = DataManager;


but i want typescript static valuable

– > this code wrong method~


// DataManager.ts
const {ccclass, property} = cc._decorator;

@ccclass(DataManager)
class DataManager{
// …

@property ({
    visible: false
})
name: string = "aaaaaa";


statics: {
    instance: null,
};

setLog(){
    cc.log(this.name);
};

}

DataManager.instance = new DataManager();

I’m sorry I missed my English.ㅜㅜ


#5

I think you should use the static keyword:

const {ccclass, property} = cc._decorator;

@ccclass(DataManager)
class DataManager{
    // …
    @property
    name: string = "aaaaaa";

    static instance: DataManager = null;

    setLog(){
        cc.log(this.name);
        cc.log(DataManager.instance);
    };

};

DataManager.instance = new DataManager();
DataManager.instance.setLog();

#6

Thank you for your response. Great. It’s working!!