Jump to content

Cannot setText after restarting scene.


ckhuang
 Share

Recommended Posts

In my game that has a pokemon-style battle system, the player would choose an attack and then text would display describing what happens. In the first battle, everything displays just fine, and there were no issues. However, when I exit the battle scene and then return back to the battle scene a second time, i get this error:

 image.png.b221c9515ba962a9a3f735fcd09616c9.png

 

here is my battle scene:

class Battle extends Phaser.Scene{
    constructor(){
        super("battleScene");
    }
 
    preload(){
        this.load.image('bear''./assets/images/bear.png');
        this.load.image('pig''./assets/images/piggy.png');
        this.load.image('monkey''./assets/images/monkey.png');
        this.load.image('player''./assets/images/sprite.png');
        this.load.image('background''./assets/images/minigameBackground.png');
 
        this.load.audio('click''./assets/sounds/click.mp3');
        this.load.audio('bearRoar''./assets/sounds/bearRoar.mp3');
        this.load.audio('Slap''./assets/sounds/slap.mp3');
        this.load.audio('Scream''./assets/sounds/scream.mp3');
        this.load.audio('Cartwheel''./assets/sounds/cartwheel.mp3');
    }
 
    create(){
        // Sets placehold background
        this.background = this.add.tileSprite(00WIDTHHEIGHT'background').setOrigin(0,0);
        
        // Creates Player
        this.player = new Player(this750500'player'1);
        this.add.existing(this.player);
        this.player.createAttacks();
        this.player.createItems();
        console.log(this.player.items);
        this.player.flipX = true;
 
        // Displays player
        this.playerHp = this.add.text(760330"", { color: '#ffffff'align: 'left'fontSize: 25}).setOrigin(0.5);
        this.playerHp.setText("HP: " + this.player.hp);
 
        // Creates Animal
        this.animal = null;
        if(DAY == 2 || DAY == 8){
            this.animal = new Bear(this125150'bear'1'str');
        } else if(DAY == 4 || DAY == 10){
            this.animal = new Pig(this125150'pig'1'wit');
        } else if(DAY == 6 || DAY == 12){
            this.animal = new Monkey(this125150'monkey'1'dex');
        }
        this.add.existing(this.animal);
 
        // Displays animal health
        this.animalHp = this.add.text(125300"", { color: '#ffffff'align: 'left'fontSize: 25}).setOrigin(0.5);
        this.animalHp.setText("HP: " + this.animal.hp);
 
        // Keeps track of whose turn it is
        this.turnCounter = 0;
        if(DAY % 7 == 0){
            REWARD = 15;
        }
 
        this.scene.launch('battleUiScene');
 
        
    }
 
    // Moves the battle along
    nextTurn(){
        this.turnCounter++;
 
        if(this.animal.isLiving && this.player.isLiving){
            if(this.turnCounter % 2 != 0){
                this.events.emit('PlayerTurn');
            } else{
                this.animal.attack(this.player);
                this.playerHp.setText("HP: " + this.player.hp);
                this.sound.add('bearRoar').play();
                this.time.addEvent({ delay: 3500callback: this.nextTurncallbackScope: this });
            }  
        } else {
            if(this.animal.isLiving == true){
                this.events.emit("Message""You've been defeated...");
                let timer = setTimeout(() =>{
                    this.exitBattle();
                }, 3500);
            } else{
                this.events.emit("Message""You won! You find yourself rewarded with " + REWARD + " dollars!");
                MONEY += REWARD;
                let timer = setTimeout(() =>{
                    this.exitBattle();
                }, 3500);
            }
        }
    }
 
    // recieves player selection and calls nextTurn()
    receivePlayerSelection(actionindex){
        if(action == 'attack'){
            if(index == 0){
                let type = "str";
                for(let i = 0i < this.player.attackText.lengthi += 6){
                    if(this.player.attacks[index] === this.player.attackText[i]){
                        let damage = this.player.attacks[index + 1];
                        if(this.player.attacks[index] === 'Slap'){
                            this.sound.add('Slap').play();
                        }
                        this.player.attack(this.animaltypedamagei);
                    }
                }
            } else if(index == 1){
                let type = "wit";
                for(let i = 2i < this.player.attackText.lengthi += 6){
                    if(this.player.attacks[index + 1] === this.player.attackText[i]){
                        let damage = this.player.attacks[index + 2];
                        if(this.player.attacks[index + 1] === 'Scream'){
                            this.sound.add('Scream').play();
                        }
                        this.player.attack(this.animaltypedamagei);
                    }
                }
            } else{
                let type = "dex";
                for(let i = 4i < this.player.attackText.lengthi += 6){
                    if(this.player.attacks[index + 2] === this.player.attackText[i]){
                        let damage = this.player.attacks[index + 3];
                        if(this.player.attacks[index + 2] === 'Cartwheel'){
                            this.sound.add('Cartwheel').play();
                        }
                        this.player.attack(this.animaltypedamagei);
                    }
                }
 
            }
            this.animalHp.setText("HP: " + this.animal.hp);
            this.time.addEvent({ delay: 3500callback: this.nextTurncallbackScope: this });
        } else if(action == 'item'){
            if(this.player.items[index] == 'Potion'){
                this.events.emit("Message""SLURRRP. You drink greedily from the potion you just pulled out of your pocket.");
                this.player.hp += 20;
                if(this.player.hp > (2 * (END - 1) + 14)){
                    this.player.hp = 2 * (END - 1) + 14;
                }
                this.playerHp.setText("HP: " + this.player.hp);
                this.player.items.splice(index1);
            }
            this.time.addEvent({ delay: 3500callback: this.nextTurncallbackScope: this });
        }
    }
 
    /*
    // Checks if battle is over by checking animal and player is living or not
    checkEndBattle(){
        let victory = true;
        if(this.animal.living == true){
            victory = false;
        }
        let loseBattle = false;
        if(this.player.living == false){
            loseBattle = true;
        }
        return victory || loseBattle;
    }
    */
 
    
    keyPressListener(event){
        if(event.code === "Space")
            this.scene.switch('menuScene');
    }
    
 
    exitBattle(){
        this.scene.destroy('battleUiScene');
        this.scene.start('cityScene');
    }
}

 

and here is my battle UI scene: that runs in with the battle scene:

class BattleUi extends Phaser.Scene{
    constructor(){
        super("battleUiScene");
    }
 
    create(){
 
        // container to hold the menus
        this.menus = this.add.container();
        this.actionsMenu = new ActionsMenu(this575725);
        this.attacksMenu = new AttacksMenu(this8725);
 
        // select current menu
        this.currentMenu = this.actionsMenu;
 
        // add menu to container
        this.menus.add(this.actionsMenu);
        this.menus.add(this.attacksMenu);
 
        // Variable to hold scene data.
        this.battleScene = this.scene.get('battleScene');
 
        // Grabs the attack arrays from BattleScene
        this.attacks = [];
        for(let i = 0i < this.battleScene.player.attacks.lengthi += 2){
            this.attacks.push(this.battleScene.player.attacks[i]);
        }
        this.items = this.battleScene.player.items;
 
        // Flag for attacksMenu to determine whether to emit attack or item
        this.selectedItems = false;
 
        // Event listener for keystrokes
        this.input.keyboard.on('keydown'this.onKeyInputthis);
 
        // Event listener for player's turn
        this.battleScene.events.on('PlayerTurn'this.onPlayerTurnthis);
 
        // Listerner for actionsMenu Confirm()
        this.events.on('SelectAttacks'this.showAttacksthis);
 
        this.events.on('SelectItems'this.showItemsthis);
 
        this.events.on('attack'this.attackEnemythis);
 
        this.events.on('item'this.useItemthis);
 
        this.sys.events.once('shutdown'this.shutdownthis);
 
        this.battleScene.nextTurn();
 
        this.message = new Message(thisthis.battleScene.events);
        this.add.existing(this.message);
        
 
        // Event listner for item messages in the ui scene.
        this.message2 = new Message(thisthis.events);
        this.add.existing(this.message2);
 
    }
 
    // Function that calls on keystrokes
    onKeyInput(event){
        if(this.currentMenu){
            if(event.code == "ArrowUp"){
                this.battleScene.sound.add('click').play();
                this.currentMenu.moveSelectionUp();
            } else if(event.code === "ArrowDown") {
                this.battleScene.sound.add('click').play();
                this.currentMenu.moveSelectionDown();
            } else if(event.code === "ArrowRight" || event.code === "Shift") {
 
            } else if(event.code === "Space" || event.code === "ArrowLeft") {
                this.currentMenu.confirm();
            }
        }   
    }
 
    // Function that calls on Player's turn.
    onPlayerTurn(){
        this.currentMenu = this.actionsMenu;
        this.actionsMenu.select();
    }
 
    // Function that calls when Player selects a type of attack they want to use.
    showAttacks(){
        this.selectedItems = false;
        this.attacksMenu.remap(this.attacks);
 
        this.currentMenu = this.attacksMenu;
        this.attacksMenu.select();
    }
 
    attackEnemy(){
        let index = this.attacksMenu.menuItemIndex;
        this.actionsMenu.deselect();
        this.attacksMenu.deselect();
        this.attacksMenu.clear();
 
        this.currentMenu = null;
        this.battleScene.receivePlayerSelection('attack'index);
    }
 
    // Displays the items player has
    showItems(){
        this.selectedItems = true;          // Set items flag to true
 
        // If player has no item, display message and return player to action menu
        if(BOUGHTPOTION == false || this.items.length < 1){
            this.events.emit("Message""You do not have any items to use...");
            let timer = setTimeout(() =>{
                this.currentMenu = this.actionsMenu;
                this.actionsMenu.select();
            }, 3500);
            return;
        }
 
        this.attacksMenu.remap(this.items);
        this.currentMenu = this.itemsMenu;
        this.attacksMenu.select();
    }
 
    useItem(){
        let index = this.itemsMenu.menuItemIndex;
        this.actionsMenu.deselect();
        this.attacksMenu.deselect();
        this.attacksMenu.clear();
 
        this.currentMenu = null;
        this.battleScene.receivePlayerSelection('item'index);
    }
 
    shutdown(){
        console.log('ui scene shutdown');
        this.input.keyboard.off('keydown');
 
        // Event listener for player's turn
        this.battleScene.events.off('PlayerTurn');
 
        // Listerner for actionsMenu Confirm()
        this.events.off('SelectAttacks');
 
        this.events.off('SelectItems');
 
        this.events.off('attack');
 
        this.events.off('item');
        this.message.destroy();
        this.message2.destroy();
    }


 
    
}

 

and this is the message class that is called to display the text: 

class Message extends Phaser.GameObjects.Container{
 
    constructor(sceneevents){
        super(scene);
        this.text = new Phaser.GameObjects.Text(scene250785"", { color: '#ffffff'align: 'left'fontSize: 25wordWrap: { width: 500basicWordWrap: true }});
        this.add(this.text);
        this.text.setOrigin(0.5);     
 
        // When an action that needs messages to appear, such as attack, it will emit an event "Message"
        // which calls the showMessage() function
        events.on("Message"this.showMessagethis);
        this.visible = true;
    }
 
    // Display the text that is passed through the event listner
    showMessage(text) {
        console.log(text);
        this.text.setText(text);
        this.visible = true;
        if(this.hideEvent)
            this.hideEvent.remove(false);
 
        // Displays text for 3.5 seconds and then hides it.
        this.hideEvent = this.scene.time.addEvent({ delay: 3500callback: this.hideMessagecallbackScope: this });
    }
 
    // Hides displayed text
    hideMessage() {
        this.hideEvent = null;
        this.visible = false;
    }
}
Link to comment
Share on other sites

  • 1 year later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...