28 lines
808 B
TypeScript
28 lines
808 B
TypeScript
import { _decorator, Component } from 'cc';
|
|
const { ccclass, property } = _decorator;
|
|
|
|
@ccclass('SingletonBase')
|
|
export abstract class SingletonBase<T extends Component> extends Component {
|
|
private static _instance: any = null;
|
|
|
|
public static getInstance<T extends Component>(this: new () => T): T {
|
|
if ((this as any)._instance === null) {
|
|
return null
|
|
}
|
|
return (this as any)._instance;
|
|
}
|
|
|
|
protected onLoad(): void {
|
|
if ((this.constructor as any)._instance) {
|
|
this.node.destroy();
|
|
return;
|
|
}
|
|
(this.constructor as any)._instance = this;
|
|
}
|
|
|
|
protected onDestroy(): void {
|
|
if ((this.constructor as any)._instance === this) {
|
|
(this.constructor as any)._instance = null;
|
|
}
|
|
}
|
|
} |