摘要
CocosCreator 物理小游戏实战的视频教程也开更啦!来哔哩哔哩关注 KUOKUO 一起学习吧!
正文
使用版本
CocosCreator 版本 2.3.4
资源划分
素材导入后进行资源分类,我这里将其分为 game 文件夹与 ui 文件夹,对应游戏场景使用资源和显示 UI 资源。

静态单例管理
UIManager 与 GameManger 分别绑定至管理节点,两者通讯靠 StaticInstance 脚本。
import GameManager from "./GameManager" import UIManager from "./UIManager"
export class StaticInstance {
static gameManager: GameManager | undefined = undefined static uiMannager: UIManager | undefined = undefined
static setGameManager(context: GameManager) { StaticInstance.gameManager = context }
static setUIManager(context: UIManager) { StaticInstance.uiMannager = context }
}
|
两个 Manager 脚本的 onLoad 中传入实例,在后面就可以相互调用了。
import { StaticInstance } from "./StaticInstance"
const {ccclass, property} = cc._decorator
@ccclass export default class GameManager extends cc.Component {
onLoad() { StaticInstance.setGameManager(this) }
}
|
在 start 及其以后即可访问实例。
import { StaticInstance } from "./StaticInstance"
const {ccclass, property} = cc._decorator
@ccclass export default class UIManager extends cc.Component {
onLoad() { StaticInstance.setUIManager(this) }
start () { console.log(StaticInstance.gameManager) }
}
|
这样就可以实现 UIManager 与 GameManager 的相互调用。
继承 UIBase
我们有 6 个 UI 要进行管理,每个 UI 都应该有显示与隐藏的方法,故抽出其共有属性与方法,实现一个 UIBase,让 6 个 UI 脚本去继承 UIBase 即可。
const {ccclass, property} = cc._decorator
@ccclass export default class UIBase extends cc.Component {
@property({ displayName: '初始显隐状态' }) isShowInit: boolean = false
onLoad() { this.isShowInit ? this.show() : this.hide() }
show() { this.node.active = true }
hide() { this.node.active = false }
}
|
拖入对应的 ui 图片完成布局,然后做成预制体。

声明两个按钮属性,写下几个方法,注意是继承 UIBase 的。
import UIBase from "./UIBase" import UIManager from "../UIManager"
const {ccclass, property} = cc._decorator
@ccclass export default class StartMenu extends UIBase {
@property(cc.Node) startButton: cc.Node = undefined @property(cc.Node) levelSelectButton: cc.Node = undefined
onLoad() { super.onLoad() }
show() { super.show() }
init(uiManager: UIManager) {
}
}
|
如下 UML 图,在 StartMenu 中就拥有了这些属性方法。

结语
视频已经开始更了哦,视频链接为:https://www.bilibili.com/video/BV1ck4y167mR
2020!我们一起进步!O(∩_∩)O~~
微信公众号
