Cocos开发采坑:
错误还原:
添加预制体,在onLoad调用生成预制体;运行报错,如下
代码如下:
// 排行榜预制体
@property(cc.Prefab)
RankingPrefab: cc.Prefab = null;
nodePHB: cc.Node = null;
leaderBoard: cc.Node = null;
onLoad() {
cc.log("onload")
this.nodePHB = cc.find("Canvas/NodePHB")
this.nodePHB.active = false;
this.leaderBoard = cc.find("ScrollView/view/content", this.nodePHB);
this.addRankingItem()
}
clickBtn(sender: cc.EventTarget, data: String) {
if (data === 'play') {
cc.log("点击了开始")
} else if (data === 'phb') {
cc.log("点击了排行榜")
this.nodePHB.active = true;
} else if (data = "closePHB") {
cc.log("点击了排行榜关闭按钮")
this.nodePHB.active = false;
}
}
// 创建 排行榜单个
addRankingItem() {
let node = cc.instantiate(this.RankingPrefab);
this.leaderBoard.addChild(node)
}
阿西吧,之前开发都没有这种情况,后面排查了发现,在游戏加载的时候,onload会被执行两次。
执行第一次的时候,资源没有加载完成,可能哈!!!,执行的第二次的时候,资源才加载完成,因此,预制体自然没有加载成功!父节点页面有加载成功,导致出现上面的错误!,解决方案,只需要加入一行代码
// 创建 排行榜单个
addRankingItem() {
if (this.RankingPrefab == null) return;//解决方案
let node = cc.instantiate(this.RankingPrefab);
this.leaderBoard.addChild(node)
}