cocos creator从零开发简单框架(08)-UI缓存

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

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

public skinPath: string = 'UIMain'
public cache: boolean = true

编辑framework/scripts/view/UIMgr.ts,添加缓存UIMap成员。

private static _uis: Map<string, UIBase> = new Map()
private static _current: UIBase

// 主UI名称
private static _uiMain: string
// UI 打开记录
private static _uiOpens: UIOpen[] = []

修改init方法,初始化时清空缓存数据。

public static init(uiMain: string) {
    this._uis.clear()

    this._uiMain = uiMain
    this._uiOpens = []
}

修改show方法,当缓存有这个UI时从缓存获取,否则从资源加载。

private static async show(cls: UIBase, uiArgs: any[]) {
    const viewName = cls.getClassName()

    let current = this._uis.get(viewName)
    if (!current) {
        current = cls
        current.uiName = viewName

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

        current.init(uiArgs)
        current.skin = cc.instantiate(uiPrefab)
        current.initDone()

        this._uis.set(viewName, current)
    } else {
        current.reset(uiArgs)
    }

    this.startShowUI(current)
}

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

private static hideUI(go: UIBase) {
    go.skin.active = false
    go.hided()

    if (go.cache) return

    this._uis.delete(go.uiName)
    go.destroy()
}

编辑scripts/UIBag.ts, 添加onInitDone方法,用于打印节点信息。

protected onInitDone(): void {
    setTimeout(() => App.showNode(cc.Canvas.instance.node, '', 0, 3), 1000) 
}

运行程序,点击背包按钮,发现UI层级下有UIMainUIBag,并且UIMain是隐藏的,说明缓存成功了。

UIMain缓存

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

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