Objects on and off

I have some ui buttons set up.

is it possible to have a script which turns on and off certain 3d objects? could be with tag or layer?

are there any examples for this?

thanks

Hi @jono3d and welcome,

Here is a tutorial on how to add logic to a UI button:

https://developer.playcanvas.com/en/tutorials/ui-elements-buttons/

To change the state of some entities using a button you can do so in the onRelease method:

(sample code)

BtnStates.prototype.onRelease = function (event) {
    event.element.textureAsset = this.hovered ? this.hoverAsset : this.originalTexture;

   var entities = this.app.root.findByTag('my-tag');
   entities.forEach(function(entity){
      entity.enabled = !entity.enabled;
   }); 
};
1 Like

thanks for that…

this is the error message I get though:

[turnlayeron.js?id=44775490&branchId=e188b5f9-1db4-44b0-8be3-9484bdda4d0f:2]: Uncaught ReferenceError: BtnStates is not defined

ReferenceError: BtnStates is not defined
at https://launch.playcanvas.com/api/assets/files/scripts/turnlayeron.js?id=44775490&branchId=e188b5f9-1db4-44b0-8be3-9484bdda4d0f:2:1

Hello @jono3d! Your function is not inside a script at this moment. It has to look something like below.
First all code that you need in your function and after that your function(s). In this case “BtnStates” should be your script name.

var BtnStates = pc.createScript('btnStates');

BtnStates.attributes.add('hoverAsset', {
    type:'asset',
    assetType:'texture'
});

BtnStates.attributes.add('activeAsset', {
    type:'asset',
    assetType:'texture'
});

// initialize code called once per entity
BtnStates.prototype.initialize = function() {
    // Get the original button texture
    this.originalTexture = this.entity.element.textureAsset;

    // Whether the element is currently hovered or not
    this.hovered = false;

    // mouse events
    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);

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

BtnStates.prototype.onRelease = function (event) {
   event.element.textureAsset = this.hovered ? this.hoverAsset : this.originalTexture;

   var entities = this.app.root.findByTag('test');
   entities.forEach(function(entity){
      entity.enabled = !entity.enabled;
   }); 
};
1 Like

brilliant thats is very helpful!

1 Like