cocos creator从零开发简单框架(18)-Panel缓存

Panel切换频繁,为了避免频繁加载资源,给Panel设置是否缓存的选项,当开启缓存时关闭Panel时把Panel对象隐藏,打开时显示Panel对象。

编辑scripts/PanelYellow.ts,开启缓存,内容如下 。

public panelShowStyle: number = AppConstants.panelShowStyle.Custom //自定义显示方式

public cache: boolean = true

编辑framework/scripts/view/PanelMgr.ts,修改show方法。

public static async show(panelCls: any, ...panelArgs: any[]) {
    TopBlock.show()

    const cls = new panelCls() as PanelBase
    const viewName = cls.getClassName()

    let current = this._panels.get(viewName)
    if (!current) {
        current = cls
        current.panelName = viewName

        const [panelPrefab, err] = await AppUtil.asyncWrap<cc.Prefab>(ResMgr.load(current.bundleName, current.skinPath))
        if (err) {
            TopBlock.hide()
            console.error(`PanelMgr.show load bundleName:${current.bundleName},skinPath:${current.skinPath},err:${err}`)
            return
        }

        current.init(panelArgs)
        current.skin = cc.instantiate(panelPrefab)
        current.initDone()

        LayerMgr.setLayer(current.skin, AppConstants.viewLayer.Panel)
        this.maskStyle(current)

        this._panels.set(viewName, current)
    } else {
        current.reset(panelArgs)

        LayerMgr.setLayer(current.skin, AppConstants.viewLayer.Panel)
    }

    current.skin.active = false
    current.showing()

    this.startShowPanel(current, current.panelShowStyle, true)
}

修改destroy方法,判断是否开启了缓存。

public static destroy(panelName: string, force: boolean = false) {
    if (!this._panels.has(panelName)) {
        console.error(`PanelMgr.destroy 面板[${panelName}]不存在`)
        return
    }

    let pb = this._panels.get(panelName)
    pb.hiding()
    pb.skin.active = false
    pb.hided()

    if (force || !pb.cache) {
        this._panels.delete(panelName)

        pb.destroy()
        pb = null
    }
}

编辑scripts/Main.ts,添加测试代码。

protected onLoad(): void {
    App.init()

    UIMgr.open(UIMain)

    PanelMgr.show(PanelYellow)
    setTimeout(() => {
        PanelMgr.hide(AppUtil.getClassName(PanelYellow))
        setTimeout(() => App.showNode(cc.Canvas.instance.node, '', 0, 3), 1000) 
    }, 1000)
}

运行程序,黄面板先是打开,过 1 秒后又自动关闭,再看控制台,发现PanelYellow这个节点还存在,但是是隐藏的,说明缓存成功了。

删除测试代码。

protected onLoad(): void {
    App.init()

    UIMgr.open(UIMain)
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!