DomDom Posted July 8, 2020 Share Posted July 8, 2020 Hey, how can I access a variable or a function that is declared in create() from a function inside a function ? For example I have the following code. How can I call my textBtnConnect from makeInteractiveAlt() import Phaser from "phaser"; import io from 'socket.io-client'; import R from '../res.js'; import config from '../../config.json'; export default class Menu extends Phaser.Scene{ constructor(){ super(R.scenes.Menu); } create(){ this.textBtnConnect = this.add.text( this.game.config.width/2, this.game.config.height/2, 'CONNECT' ); this.textBtnConnect.on('pointerdown', () => { this.textBtnConnect.disableInteractive() makeInteractive(); // Calling function works this.someRandomFunction() // Calling function works }); function makeInteractive(){ // TypeError: Cannot read property 'textBtnConnect' of undefined this.textBtnConnect.setInteractive() // Uncaught ReferenceError: textBtnConnect is not defined textBtnConnect.setInteractive() } } update(){} render(){} someRandomFunction(){ // works this.textBtnConnect.setInteractive() makeInteractiveAlt() // Calling function works function makeInteractiveAlt(){ // TypeError: Cannot read property 'textBtnConnect' of undefined this.textBtnConnect.setInteractive() // Uncaught ReferenceError: textBtnConnect is not defined textBtnConnect.setInteractive() } } } Link to comment Share on other sites More sharing options...
Darko Posted July 9, 2020 Share Posted July 9, 2020 Hello, in your example I guess you need to use setInteractive() before using .on('pointerdown'... About your question there are different ways you can do: Try passing it as arg to the function function makeInteractive(btn) { //use btn here... } and callit like makeInteractive(this.textBtnConnect) Or you can use arrow function and use it with 'this' const makeInteractive = () => { // use this.textBtnConnect here } Link to comment Share on other sites More sharing options...
Recommended Posts