[SOLVED] Communicate HTML button with a script function

in all examples buttons are communicated with script with using EventListener. I wanted to do many buttons with many actions and I wanted to prevent many EventListeners.

That`s why I wanted to do buttons triggered by onclick.

like this one:

<div class='button' onclick="htmlChangeDiffuseFromColorToColor('boxName',[255,0,255]);">BUTTON</div>
<div class='text'>
    Hit the button to change color to pink<br />

In script binded to that HTML I wanted to do a function which will do something for me.
For example will change box color like this:

var Ui = pc.createScript('ui');

Ui.attributes.add('css', {type: 'asset', assetType:'css', title: 'CSS Asset'});
Ui.attributes.add('html', {type: 'asset', assetType:'html', title: 'HTML Asset'});

Ui.prototype.initialize = function () {
    var style = document.createElement('style');
    style.innerHTML = this.css.resource || '';
    this.div = document.createElement('div');
    this.div.innerHTML = this.html.resource || '';

Ui.prototype.htmlChangeDiffuseFromColorToColor = function(objectName, rgbColor) {
        var obj = pc.app.root.findByName(objectName);
        if (obj && obj.render) {      
            var material = obj.render.meshInstances[0].material;
            if (material) {
                material.diffuse.set(rgbColor[0]/255, rgbColor[1]/255, rgbColor[2]/255);

That throws error:

QUESTION: Please tell me how to point HTML button onclick to get into that Ui script function? I know how to create global function but I would like to prevent it.

My fork to this question: PlayCanvas | HTML5 Game Engine

In other words, I need to find a way to find entity.script access from the position of the HTML button.
I need to go up in structure and go straight to the function inside a bind script. For now only global functions work for me and that is not elegant way.

OK. I`ve solved it :slight_smile: this is the answer to my question:

<div class='button' onclick="pc.app.root.findByName('html+css').script.entity.script.ui.htmlChangeDiffuseFromColorToColor('boxName',[255,0,255]);">BUTTON</div>
<div class='text'>
    Hit the button to change color to pink<br />

My solved fork to this question: PlayCanvas | HTML5 Game Engine

1 Like