Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support parameter passing in component constructor #2158

Merged
merged 3 commits into from
Jul 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions packages/core/src/Entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,11 +203,15 @@ export class Entity extends EngineObject {
/**
* Add component based on the component type.
* @param type - The type of the component
* @param args - The arguments of the component
* @returns The component which has been added
*/
addComponent<T extends Component>(type: new (entity: Entity) => T): T {
addComponent<T extends new (entity: Entity, ...args: any[]) => Component>(
type: T,
...args: ComponentArguments<T>
): InstanceType<T> {
ComponentsDependencies._addCheck(this, type);
const component = new type(this);
const component = new type(this, ...args) as InstanceType<T>;
this._components.push(component);
component._setActive(true, ActiveChangeFlag.All);
return component;
Expand Down Expand Up @@ -751,3 +755,10 @@ export class Entity extends EngineObject {
return this._invModelMatrix;
}
}

type ComponentArguments<T extends new (entity: Entity, ...args: any[]) => Component> = T extends new (
entity: Entity,
...args: infer P
) => Component
? P
: never;
4 changes: 2 additions & 2 deletions packages/xr/src/XRManagerExtended.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export class XRManagerExtended extends XRManager {
override addFeature<T extends new (xrManager: XRManagerExtended, ...args: any[]) => XRFeature>(
type: T,
...args: TFeatureConstructorArguments<T>
): XRFeature | null {
): InstanceType<T> | null {
if (this.sessionManager._platformSession) {
throw new Error("Cannot add feature when the session is initialized.");
}
Expand All @@ -69,7 +69,7 @@ export class XRManagerExtended extends XRManager {
const feature = features[i];
if (feature instanceof type) throw new Error("The feature has been added");
}
const feature = new type(this, ...args);
const feature = new type(this, ...args) as InstanceType<T>;
this._features.push(feature);
return feature;
}
Expand Down
Loading