3.8.3前的版本存在该问题,个人认为是一个bug未来可能会修复。
问题点:使用官方推荐的eventTarget来处理事件。当eventTarget不在同一个类中,无法调用emit触发事件
问题代码:
GameControl.ts
import { _decorator, EventTarget, Label } from 'cc';
const eventTarget = new EventTarget();
@ccclass('GameControl')
export class GameControl extends Component {
// 金币数量
@property(Label)
coinNumber: Label = null;
protected onLoad(): void {
eventTarget.on("addCoin", this._addCoin, this);
}
public _addCoin(number: number) {
let coin = Number(this.coinNumber.string);
coin += number;
this.coinNumber.string = coin.toString();
}
}
Enemy.ts
import { _decorator, CCInteger, Collider2D, Component, Contact2DType, IPhysics2DContact, Node, Vec3 } from 'cc';
const eventTarget = new EventTarget();
@ccclass('Enemy')
export class Enemy extends Component {
start() {
let collider = this.getComponent(Collider2D);
if (collider) {
collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
}
}
...
onBeginContact (selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
// 先处理自己的逻辑
let bullet = otherCollider.node;
let attack = bullet.getComponent(Bullet).attack;
if (this.health - attack <= 0) {
// 金币增加
eventTarget.emit("addCoin", 1);
this.node.destroy();
}
// 处理子弹
otherCollider.node.destroy();
}
}
解决办法:将eventTarget导出,在使用的地方导入eventTarget。
GameControl.ts
import { _decorator, EventTarget, Label } from 'cc';
// 导出
export const eventTarget = new EventTarget();
@ccclass('GameControl')
export class GameControl extends Component {
// 金币数量
@property(Label)
coinNumber: Label = null;
protected onLoad(): void {
eventTarget.on("addCoin", this._addCoin, this);
}
public _addCoin(number: number) {
let coin = Number(this.coinNumber.string);
coin += number;
this.coinNumber.string = coin.toString();
}
}
Enemy.ts
import { _decorator, CCInteger, Collider2D, Component, Contact2DType, IPhysics2DContact, Node, Vec3 } from 'cc';
// 导入
import { eventTarget } from '../Game/GameControl';
@ccclass('Enemy')
export class Enemy extends Component {
start() {
let collider = this.getComponent(Collider2D);
if (collider) {
collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
}
}
...
onBeginContact (selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
// 先处理自己的逻辑
let bullet = otherCollider.node;
let attack = bullet.getComponent(Bullet).attack;
if (this.health - attack <= 0) {
// 金币增加
eventTarget.emit("addCoin", 1);
this.node.destroy();
}
// 处理子弹
otherCollider.node.destroy();
}
}