CocosCreator中,基本代码模板GameSys

说明

在组件Launch的onLoad中初始化GameSys:创建其单例;在onDestroy中销毁GameSys。

代码

GameSys.ts

import { EventTarget } from 'cc';
export class GameSys
{ 
    private static _instance: GameSys;
    public static get instance(): GameSys
    {
        return this._instance;
    }

    private _eventTarget: EventTarget;
    public get eventTarget(): EventTarget {
        return this._eventTarget;
    }

    public static init(): void
    { 
        if (!GameSys.instance)
        { 
            this._instance = new GameSys();
            

            console.info('初始化GameSys');
        }
    }

    private constructor()
    {
        this._eventTarget = new EventTarget;
    }

    public myDestroy(): void
    {
        if (GameSys.instance == this)
        { 
            this._eventTarget = null;
            GameSys._instance = null;

            console.info('销毁GameSys');
        }
    }
}

Launch.ts

import { _decorator, Component, Node } from 'cc';
import { GameSys } from './Sys/GameSys';
const { ccclass, property } = _decorator;

@ccclass('Launch')
export class Launch extends Component 
{
    onLoad()
    {
        this.init();
    }

    onDestroy()
    { 
        this.myDestroy();
    }

    private init(): void
    {
        GameSys.init();
    }
    
    private myDestroy(): void
    { 
        GameSys.instance.myDestroy();
    }
}

推荐阅读更多精彩内容