原文链接: cocos 组件/节点抽象和复用
cocos 里面的逻辑单元是节点, 即使用结点来抽象逻辑
效果如下, 复用一个计数器节点
先实现计数器节点, 主要是一个按钮和显示数值的label
const { ccclass, property } = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {
@property(cc.Label)
label: cc.Label = null;
@property
text: string = "hello";
@property
count: number = 0;
@property(cc.Button)
inc: cc.Button = null;
start() {
this.label.string = this.count + "";
this.inc.node.on(cc.Node.EventType.MOUSE_DOWN, () => {
console.log("inc", this.count);
this.label.string = ++this.count + "";
});
}
setCount(c = 0) {
console.log("setCount", c);
this.label.string = c + "";
this.count = c;
}
}
然后把这个节点从上面拖下来, 变成prefab, 这个prefab相当于一个类, 我们可以通过这个来实例化不同的节点, 同时节点之间的数据是分开的
const { ccclass, property } = cc._decorator;
@ccclass
export default class NewClass extends cc.Component {
@property(cc.Label)
label: cc.Label = null;
@property(cc.Button)
btn: cc.Button = null;
@property
text: string = "hello";
@property(cc.Prefab)
counterFab: cc.Prefab = null;
@property
itemCount: number = 0;
start() {
this.btn.node.on(cc.Node.EventType.MOUSE_DOWN, () => {
console.log("ee");
const node = cc.instantiate(this.counterFab);
node.getComponent("ItemScript").setCount(this.itemCount);
node.x = this.itemCount * 100 + -300;
this.itemCount++;
this.node.addChild(node);
});
}
}