[ENGINE ONLY] Get script data from SceneItem

Hi, is it possible to read all script info from a SceneItem from scene JSON?

"scripts": {
   "rotate": {
     "enabled": true,
     "attributes": {
       "x": "10",
       "y": "20",
       "z": "30"
     }
   }
}
SceneRegistry.loadSceneHierarchy(
        'scenes/basic.json',
        function (err, sceneItem) {
          if (err) {
                // error
                console.log('Error: ', err);
          }
          app.fire('preload:end');
          var scripts = sceneItem.findComponents('script');

          app.scripts.add(scripts[0]);
          console.log(sceneItem, scripts[0]._scriptsData);
          app.start();
        }
);


You should be able to load scene jsons that are published from the Editor via the Scene Registry using loadSceneHierarchy. However, you need to add the scene item to the registry first via https://developer.playcanvas.com/api/pc.SceneRegistry.html#add

Is the script rotate already added to the script registry via pc.createScript or pc.registerScript

If not, that’s probably why you are seeing the issue you are seeing.

Are you doing this before app.start()?

If you need the raw json data, you can get that from sceneItem.data after loading

Thank you for your reply @yaustar. Well thats the point I do not know upfront what scripts are in the scene and want to get their names and attributes after loading the scene and then add the scripts…

Yes by now its before app.start()… Should it be after?

Looking at the boilerplate for the Editor projects, loadScene is used because it loads the hierarchy and scene settings but doesn’t initialize the components/scripts etc as that’s done in app.start()

app.loadScene(SCENE_PATH, function (err, scene) {
    if (err) {
        console.error(err);
    }

    app.start();
});

Whereas loadSceneHierarchy will fire the events to initialize the entities

https://github.com/playcanvas/engine/blob/main/src/framework/scene-registry.js#L304

I don’t know if anything bad will happen if you use loadSceneHierarchy before app.start but for ‘safety’, I would do it after app.start() or use loadScene instead.

As for finding the script names, I did a quick test and unfortunately, the information you need is in the private API. We don’t have an API to get the script names that not loaded yet.

1 Like

Thanks for the info @yaustar. A pitty that it’s in private API, I have to/will find a workaround.
I am confidend at least for now that I will have something that work for me.

Thanks for all the effort!

@yaustar Can you please give me an example on how to use the ScriptHandler?
https://developer.playcanvas.com/api/pc.ScriptHandler.html#load

You shouldn’t need to use it directly.

To load script assets, create an asset of script type and use the asset registry to load the asset.

1 Like