cocos-engine icon indicating copy to clipboard operation
cocos-engine copied to clipboard

node.ts的addComponent()方法可以考虑将组件类的可选参数补上吗?

Open wwzhg77777 opened this issue 7 months ago • 0 comments

Use Case

Problem Description

cocos\scene-graph\node.ts#1126

const component = new constructor();
component.node = (this as unknown as Node); // TODO: HACK here
this._components.push(component);
if (EDITOR && EditorExtends.Node && EditorExtends.Component) {
    const node = EditorExtends.Node.getNode(this._id);
    if (node) {
        EditorExtends.Component.add(component._id, component);
    }
}
this.emit(NodeEventType.COMPONENT_ADDED, component);
if (this._activeInHierarchy) {
    (cclegacy.director as Director)._nodeActivator.activateComp(component);
}
if (EDITOR_NOT_IN_PREVIEW) {
    component.resetInEditor?.();
}

源码里边,new constructor()时把 ...args 可选参数忽略了。 假设我有一个子类A继承了Component类,给子类A的构造函数增加了若干参数,在执行Node.addComponent(A)时,子类A的构造函数是需要入参的,这时运行不会报错,但是忽略了子类A构造函数的参数。

期望:cocos官方可以考虑下优化这个建议不?

Proposed Solution

预期效果: 增加一个实现方法,如 Node.addComponent(A, ...args)

public addComponent<T extends Component>(classConstructor: Constructor<T>, ...args: any[]): T;

node.ts#1126

const component = new constructor(...args);

How it works

No response

Alternatives Considered

Additional Information

No response

wwzhg77777 avatar Apr 28 '25 18:04 wwzhg77777