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 协议》,转载必须注明作者和本文链接