How to change scenes from a button?

Okay, so I have a code to change scenes with the press of a button and for some reason, it doesn’t work!

Here’s my code:

var Playbutton = pc.createScript('playbutton');
Playbutton.attributes.add("sceneId", {type: "string", default: "0", title: "Scene ID To Load"});
Playbutton.prototype.initialize = function() {
    this.entity.element.on('mouseenter', this.onEnter, this);
    this.entity.element.on('mousedown', this.onPress, this);
    this.entity.element.on('mouseup', this.onRelease, this);
    this.entity.element.on('mouseleave', this.onLeave, this);
};
Playbutton.prototype.onPress = function(event) {
    var oldHierachy = this.app.root.findByName("Root");
    oldHierachy.destroy();
    this._loadSelectedScene();
};
Playbutton.prototype._loadSelectedScene = function () {
    if (!this._loadingScene) {
        this._loadingScene = true;
        this._loadSceneButtonactive = false;
        var self = this;
        this.app.scenes.loadSceneHierarchy(scene.url, function (err, loadedSceneRootEntity) {
            if (err) {
                console.error(err);
            } else {
                loadedSceneRootEntity.reparent(this.sceneId);    
                self._loadingScene = false;
                self._loadSceneButton.active = true;
            }
        });
    }
};

Hi @Joe_Hanks and welcome! Please check if the ‘Use Input’ option of your element component is enabled.

No, I can do other stuff with buttons like make the button disappear when pressed.
I think it’s the _loadSelectedScene function that is causing an error.

Do you get an error on this line?

Yeah, and everything inside it.

This is because the variable scene hasn’t been defined.

Looking at the project sample for loading scenes at https://developer.playcanvas.com/en/tutorials/changing-scenes/

We can see the code for loading a scene: https://playcanvas.com/editor/code/437633?tabs=5632645

Looks like you are missing this line:

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

Where sceneName is the name of the scene that you want to load.

It says that scene.url is invalid.

Can you share your project please?

The scene id set in the Editor for the script attribute is most likely to be incorrect. scenes.find takes the name of the scene, not the id as well