casey
#1
Hi guys,
I am a novice, im trying call a function in a script on another entity in the following way:
otherEntity.script.scriptName.myFunction()
i got this error:
Uncaught TypeError: Cannot read property ‘script’ of undefined
How do I call a function correctly in a script on another Entity?
help me,plz…
It’s saying that otherEntity
is undefined. Your line of thinking is correct on how to call the function on another script instance though.
casey
#3
but i have definded the entity.
The error says otherwise. Can you post a link to the project please?
casey
#5
thx for your replay.
here is code:
the ui.js:
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.attributes.add('atenza', {type: 'entity'});
Ui.prototype.initialize = function () {
var style = document.createElement('style');
document.head.appendChild(style);
style.innerHTML = this.css.resource || '';
this.div = document.createElement('div');
this.div.classList.add('container');
this.div.innerHTML = this.html.resource || '';
document.body.appendChild(this.div);
this.bindEvents();
};
Ui.prototype.bindEvents = function() {
var button = this.div.querySelector('.button');
if (button) {
button.addEventListener('click', function() {
console.log('button clicked');
this.atenza.script.tweenMaterial.reset();
}, false);
}
};
the “atenza” is an entity reference, the"tweenMaterial" is a script on the atenza entity, reset() is a function in the tweenMaterial script.
if (button) {
button.addEventListener('click', function() {
console.log('button clicked');
this.atenza.script.tweenMaterial.reset();
}, false);
}
As the callback is in a lambda function, the this
reference isn’t pointing to the same this
outside the function.
The way to get around this is to declare a new variable pointing to this
and use that instead in the callback so the lambda can capture the variable.
if (button) {
var self = this;
button.addEventListener('click', function() {
console.log('button clicked');
self.atenza.script.tweenMaterial.reset();
}, false);
}
casey
#8
it’s work! thx!
I am a newbie, please bear with me.