Is there a way to pass value to class constructor in another way?

I’m adding a script instance at runtime like this official example.

If you want to set the value to an attribute on construction, you actually need to do this: image

But, this is also required to add this at the end of your JS class file, to make attributes accessible on creation:

image

Is there a way to do something like this instead?
image

Because attributes need to be set after registering the class, I do that at the end of the file. The problem is that I only need to do that on attributes that need to be set on construction. The other attributes can be set directly or by the “setter” method, meaning that I need the declare my attributes in 2 ways.

It is not a blocker actually, I’m just looking to improve the readability and organization of my code.

Thank you for the help.

If you are deriving from pc.ScriptType, then it is not possible.

You can use a normal class, instead, then you can pass needed attributes to constructor. You will not have access to this.app / this.entity inside of them, though, and the engine will not automatically execute predefined methods, like initialize() - you will have to take care of those by yourself.

I made a small example to demonstrate it:
https://playcanvas.com/project/790659/overview/script-inheritance-2

2 Likes

It really is a compromise to be made. I have to assess whether it is worth it or not.

Thank you for your answer.

1 Like