常规
export default class Singleton{
private static instance: any = null
public static getInstance<T extends {}>(this: new () => T): T {
if(!(<any>this).instance){
(<any>this).instance = new this();
}
return (<any>this).instance;
}
constructor() { }
}
继承cc.Component
export default class SingletonComponent<T> extends cc.Component {
private static instance: any = null
public static getInstance<T extends cc.Component>(this: new () => T): T {
if ((<any>this).instance == null) {
let newNode = new cc.Node(this.name)
;(<any>this).instance = newNode.addComponent(<any>this)
cc.director.getScene().addChild(newNode)
}
return (<any>this).instance
}
onDestroy() {
;(<any>this).instance = null
}
}
评论区