美文网首页js css html
CocosCreator中的单例

CocosCreator中的单例

作者: 全新的饭 | 来源:发表于2022-10-20 17:41 被阅读0次

不继承Component

提供只读属性instance,在初次调用时,创建实例_instance。
提供公有方法myDestroy,供外界主动调用,销毁本单例。
示例:Utils.ts

import { assetManager, ImageAsset, SpriteFrame } from "cc";

export class Utils
{ 
    private static _instance: Utils;
    public static get instance():Utils
    { 
        if (!this._instance)
        { 
            this._instance = new Utils();
        }
        return this._instance;
    }

    public myDestroy(): void
    { 
        if (Utils.instance == this)
        { 
            Utils._instance = null;
        }
    }

    // 根据图片链接,获取图片
    public urlToSpriteFrame(url:string, callback: (spriteFrame:SpriteFrame)=>void): void
    { 
        assetManager.loadRemote<ImageAsset>(url, (err, texture) =>
        {
            if (!err)
            {
                callback(SpriteFrame.createWithImage(texture));
            }
        });
    }

    // 将秒数显示为'xx:xx:xx'的形式
    public formatTime(totalSeconds: number): string {
        let hours: number = this.rounding((totalSeconds / 3600));
        let hh: string = (hours < 10 ? "0" + hours : hours).toString();
        let minutes: number = this.rounding((totalSeconds - hours * 3600) / 60);
        let mm: string = minutes < 10 ? "0" + minutes : minutes.toString();
        let seconds: number = this.rounding(totalSeconds - hours * 3600 - minutes * 60);
        let ss: string = seconds < 10 ? "0" + seconds : seconds.toString();
        let num: string = hh + ":" + mm + ":" + ss;
        return num;
    }
    private rounding(num: number): number {
        return Math.floor(num);
    }

    // 整数转汉字
    public intToCN(num: number): string {
        let words = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
        let adds = ["", '十', '百', '千', '万', '十', '百', '千', '亿'];
        if (words[num]) {
            return words[num];
        }
        else if (num > 10 && num < 20) {
            let numStr = num.toString();
            let n:number =  Number(numStr.substring(1, 2));
            let result = adds[1] + words[n];
            return result;
        }
        else if (num > 10) {
            let result = "";
            let numStr = num.toString();
            for (var i = 0; i < numStr.length; ++i) {
                let n:number = Number(numStr.substring(i, i + 1));
                let m = numStr.length - i - 1;
                result += words[n] + adds[m];
            }
            return result;
        }
        else return "零";
    }
}

继承Component,手动放到某个场景中

在init()方法中,将单例设置为this,并将this.node设置为常驻节点。
如果单例已存在,则销毁本节点(避免场景中误放了多个)。

 director.addPersistRootNode(this.node);

在start()中调用init。

在myDestroy()方法中,如果单例是this,将单例设置为null,销毁本节点。
在onDestroy()中调用myDestroy()。
示例:GM.ts

import { KeyCode, EventKeyboard, input, Input, _decorator, Component, director } from "cc";
import { Level } from "./Fish/Level";
import { MyFish } from "./Fish/MyFish";
const { ccclass, property } = _decorator;

@ccclass('GM')
export class GM extends Component {
    private static _instance: GM;
    public static get instance(): GM {
        return this._instance;
    }

    private static readonly autoLevelWinKey: KeyCode = KeyCode.KEY_Q;

    start() {
        this.init();
    }
    onDestroy() {
        this.myDestroy();
    }

    private init() {
        if (!GM.instance) {
            GM._instance = this;
            director.addPersistRootNode(this.node);
            input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this);
        }
        else {
            this.node.destroy();
        }

    }

    public myDestroy(): void {
        if (GM.instance == this) {
            input.off(Input.EventType.KEY_DOWN, this.onKeyDown, this);
            GM._instance = null;
            this.node.destroy();
        }
    }

    private onKeyDown(event: EventKeyboard): void {
        if (event.keyCode == GM.autoLevelWinKey) {
            this.autoLevelWin();
        }
    }

    // 自动过关
    private autoLevelWin(): void {
        const fishes: MyFish[] = director.getScene().getComponentsInChildren(MyFish);
        const level: Level = director.getScene().getComponentInChildren(Level);

        if (fishes && level) {
            for (const f of fishes) {
                if (!f.isRight) {
                    f.turnOver(true);
                }
            }
            level.checkIsWin();
            console.info('GM指令:自动过关 成功!');
        }
        else {
            console.info('GM指令:自动过关 失败!');
        }
    }
}

继承Component,第一次调用时自动生成

在第一次获取单例时,构建节点:设置为常驻节点,init()……
在myDestroy()中,销毁本节点,将单例设置为null。在onDestroy()中调用myDestroy()。
示例:CocosCreator中,简单的音频播放控制

相关文章

网友评论

    本文标题:CocosCreator中的单例

    本文链接:https://www.haomeiwen.com/subject/jumuzrtx.html