How to change object on click of a button?


I need a button to control the tutorial of switching a product model, thank you all

Hi @changhua0504 and welcome!

The first step is to create a button. On the page below you can read how to create a button using UI elements.

Do you want to change the model or only the material? Below an example project about changing the material.

I want to change the model.


I want to change to this model through this button.

There are a couple of ways to achieve this. It depends on your requirements which is the best option for you. Personally, I would add all the models as separate entities in the scene and only enable the entity I need. (Please note that all models are loaded when loading your project).

This was discussed here:

1 Like
var BtnnewScene = pc.createScript('btnnewScene');

BtnnewScene.attributes.add("sceneId", {type: "string", default: "0", title: "Scene ID to load"});

BtnnewScene.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);

this.entity.element.on('touchstart', this.onPress, this);
this.entity.element.on('touchend', this.onRelease, this);
};

BtnnewScene.prototype.onPress = function(event) {
    var oldHierarchy = this.app.root.findByName ('Root');

        oldHierarchy.destroy ();
        this.loadScene (this.sceneId, function () {

        });
};

BtnnewScene.prototype.update = function(dt) {

};

BtnnewScene.prototype.loadScene = function (id, callback) {
    var url = id + ".json";
    this.app.loadSceneHierarchy(url, function (err, parent) {
        if (!err) {
            callback(parent);
        } else {
            console.error (err);
        }
    });
};

used the scene replacement script of this project, and then entered the name of my other scene, but it still didn’t work after running it.



It seems like you are now trying to change the scene instead of the object?

To change a scene all you need is the code below nowadays.

this.app.scenes.changeScene('Some Scene Name');





It’s still doesn’t’ work.

You took me a little too literally now. You must use the code on the right place in your script of course.

Haha, I’m just an animator and know nothing about programming. Can you please tell me how to operate it?

I’m afraid you need some basic knowledge. Below the manual page and an example project. In the ‘menu’ scene of the example project you will find a script where the line of code is used on button click.

https://playcanvas.com/project/924351/overview/switch-full-scene-example

It works! thank you so much

1 Like