CocosCreator版本:2.3.4
一般游戲都有圖層管理,比如
- sceneLayer 場景層
- panelLayer 彈框層
- tipLayer 提示框層
cocos里的場景不是持久化的,每次切換都會自動destroy,如果在場景上放這些圖層,那么每個scene都要放一遍?然后再獲取,這樣很麻煩。
加載場景使用的是cc.director.loadScene,scene的容器node貌似是director上的一個nodeActivator
現在如果不考慮scene的容器或者cocos的頂層容器。我想一想兩種圖層管理的方法。
一、只有一個scene
整個游戲一個scene,就是游戲入口的scene,在這個scene上放sceneLayer等圖層的node,這個入口scene相當于egret和laya的stage。
然后所有場景scene和彈框模塊,都做成預制件prefab,每次顯示都addChild到入口scene的相應圖層上就行了。
二、使用常駐節點
比如我在場景1,放置sceneLayer等圖層。為了方便顯示,我每個圖層加了個單色。
常駐節點必須在根節點下,也就是和canvas同級。把3個圖層設置為常駐節點。
onLoad(){ cc.game.addPersistRootNode(cc.find("sceneLayer")); cc.game.addPersistRootNode(cc.find("panelLayer")); cc.game.addPersistRootNode(cc.find("tipLayer")); }
然后切換場景,在新場景中,仍然可以顯示并獲取到sceneLayer等圖層。
onLoad(){ console.log(cc.find("sceneLayer")); //輸出sceneLayer的cc.Node }
利用常駐節點,我們可以在入口場景中放置sceneLayer等圖層。用圖層管理類保存引用。
三、最佳實踐
圖層管理類,單例
export default class LayerManager extends cc.Component { private static instance:LayerManager; public static ins():LayerManager{ if(this.instance == null){ this.instance = new LayerManager(); } return this.instance; } public panelLayer:cc.Node; public tipLayer:cc.Node; }
在入口場景中設置常駐節點layer, 用圖層管理類保存引用。以備之后使用。
@ccclass export default class Helloworld extends cc.Component { onLoad(){ cc.game.addPersistRootNode(cc.find("sceneLayer")); cc.game.addPersistRootNode(cc.find("panelLayer")); cc.game.addPersistRootNode(cc.find("tipLayer")); LayerManager.ins().panelLayer = cc.find("panelLayer"); LayerManager.ins().tipLayer = cc.find("tipLayer"); } }
以上就是如何在CocosCreator中利用常駐節點做圖層管理的詳細內容,更多關于CocosCreator常駐節點做圖層管理的資料請關注服務器之家其它相關文章!
原文鏈接:https://blog.csdn.net/qq_43287088/article/details/107351609