[SOLVED] Initialise a script with specified parameters

Hello all,

I am trying to do something which probably has a very short and elegant answer but the for the life if me I cannot see it.

I need to initialize a script, in code (this is a project being done in a web environment, not the PC editor), and pass some variables to the script to set internally either whilst being created or immediately after.

Originally I tried the following:

app.systems.script.addComponent ( cameraEntity, 
{
	scripts: [{url: 'JS/cubeCamera.js'}]
});
cameraEntity.script.transitionManager.setMyParams(myParams);

However, given the addComponent is incomplete (I’m guessing its asynchronous?) at the point my program tries to set the parameters the method is undefined (still loading?).

Ideally what i want is something similar to the built-in camera script where you can do:

cameraEntity.addComponent("camera", 
{
	clearColor: new pc.Color(0.2, 0.0, 0.0),
	fov: 60
});

The above method of attributes is unfortunately not suitable because I need to pass some more complex data than the provided types, such as a material array.

Any advice on how to do this is most definitely welcome.

The addComponent() is usually synchronous so your code should work. However, I suspect you do not have the script JS/cubeCamera.js loaded before calling addComponent which would make it asynchronous.

When running from the Editor we handle the script loading for you so code is loaded before the application starts.


Note: your initial code is using an older style. Newer style is this:

cameraEntity.addComponent("script",  { 
    //...
}); 

Hi @dave

Thanks for the reply :slight_smile:

I’ve tried several times doing things your way but I then get an error from the system that the script “doesn’t exist”, which suggests either a loading problem or that I have missed something. I don’t suppose you know of any examples that go through script creation and attachment for offline playcanvas programming?
I’ve been looking through the engine code and It looks like i should be doing something with a scriptComponent type which the script is attached to, but I can’t see anything that suggests how to do that.

Any help here is much appreciated, I haven’t been able to make any progress for days now on something that seems simple :frowning:

Hmm

OK, I’ve just taken a closer look. Seem there are two issues here.

  1. Scripts all need to be loaded with our resource loader for script components to behaviour synchronously. This is because the script name needs to be linked to the URL. So load your scripts like this:

app.loader.load("path/to/script.js", "script", function (err, ScriptObject) {});

  1. There is a bug (github) which is preventing this from working correctly. Once the bug is fixed it should work as expected.

Sorry about that!

Just pushed a fix for that bug.

Thanks @dave and @vaios much appreciated :smile: