[SOLVED] Cannot Switch Scenes Using Menu Buttons

Hi! I can’t seem to enable the switching of my scenes from a main menu to a level. I wrote the code as accurately as I can and have tried doing it over but it just won’t seem to work. My target is to switch from the ‘start’ button going to ‘level1’ but it just won’t switch even after parsing and refreshing. Here is the screenshot of the interface and then the code below for reference:

The level I want to go to is ‘level1’

var ChangeSceneClick = pc.createScript('changeSceneClick');

ChangeSceneClick.attributes.add('sceneName',{type: 'string',default: '', title: 'Scene Name to Load'});


// initialize code called once per entity
ChangeSceneClick.prototype.initialize = function() {
    // change scenes on button click 
    this.app.root.findByName('start').element.on('click'), function (event){
        this.loadScene(this.sceneName);
    }, this;

};

// function that loads the set scene
ChangeSceneClick.prototype.loadScene = function(sceneName) {
        // Get a reference to the scene's root object
    var oldHierarchy = this.app.root.findByName('uiRoot');

    //Get the path to the sceneName 
    var scene = this.app.scenes.find(sceneName);

    // load the scenes entity hierarchy
    this.app.scenes.loadSceneHierarchy(scene.url, function (err, parent){
        if (!err) {
            oldHierarchy.destroy();

        }else{
            console.error(err);
        }
    });
};```

Hey Renee, Seems like you are not listening to the click event of the start button. You have closed the brackets after “click” which will not attach the function next to it.
This is how you can do it

this.app.root.findByName("start").element.on("click", function () {
        console.log("ok");
        this.loadScene(this.sceneName);
    }, this);
1 Like

It’s better to use this function.

this.app.scenes.changeScene(‘Some Scene Name’);

If the scene data is not already loaded, this function will:

  • Make the asynchronous network request for the new scene data.
  • When the scene data is loaded, it will delete all child entities from the application root node (destroying the existing scene hierarchy).
  • Call loadSceneSettings which is now synchronous as the scene data is loaded.
  • Call loadSceneHierarchy which is now synchronous as the scene data is loaded.

I added my thoughts to what @saif said.

2 Likes

Hi Saif! Thanks for this!! That really helped a lot!