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
,添加缓存 UI
的 Map
成员。
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
层级下有 UIMain
和 UIBag
,并且 UIMain
是隐藏的,说明缓存成功了。
本作品采用《CC 协议》,转载必须注明作者和本文链接