- 1、最简单单例写法
onLoad () {
//写法1
if(GameMgr.instance == null){
GameMgr.instance = this;
}
else{
this.destroy();
return;
}
}
调用方式:
GameMgr.instance.方法名();
- 2、懒汉式写法
private static _instance: GameMgr = new GameMgr();
public static getInstance() {
if(!this._instance){
console.log("new GameMgr");
this._instance = new GameMgr();
}
return this._instance;
}
onLoad () {
GameMgr._instance = this;
}
调用方式:
GameMgr.instance.方法名();
- 3、单独基类脚本方式
const {ccclass, property} = cc._decorator;
//Singleton.ts
@ccclass
export class Singleton<T>extends cc.Component{
private static instance: any = null;
public static GetInstance<T>(c: { new(): T }): T
{
if (this.instance == null)
{
this.instance = new c();
}
return this.instance;
}
onLoad () {
console.log("11");
Singleton.instance = this;
}
}
onLoad () {
super.onLoad();
}
继承于cc.Component,可挂载在场景中的物体。
调用方式:
GameMgr.GetInstance(GameMgr).方法名();
网友评论