Button managing in different scene

Hi, I have created the main_menu scene which can lead to game_scene and about_scene. That was easy, the thing is when I wanted to load the main_menu scene by clicking the back button from about_scene, it didn’t work. I have a script to manage all the buttons like this

import { _decorator, Component, director, find, Input, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('ButtonManager')
export class ButtonManager extends Component {
    @property(Node) public startBtn: Node | null = null;
    @property(Node) public aboutBtn: Node | null = null;
    @property(Node) public backBtn: Node | null = null;

    protected onLoad(): void {
        this.startBtn = find("Canvas/Text Holder/Start Button") as Node;
        this.aboutBtn = find("Canvas/Text Holder/About Button") as Node;
        this.backBtn = find("Canvas/Button/Back Button") as Node;

        this.startBtn.on(Input.EventType.TOUCH_START, this.startDown, this);
        this.aboutBtn.on(Input.EventType.TOUCH_START, this.aboutDown, this);
        this.backBtn.on(Input.EventType.TOUCH_START, this.backDown, this);
    }

    //#region BUTTON PRESSED
    startDown(): void {
        // this.loadGameScene();
        console.log("hehehehe");
    }

    aboutDown(): void {
        this.loadAboutScene();
    }

    backDown(): void {
        this.backToMainGame();
    }
    //#endregion

    //#region SCENE LOADING
    loadGameScene(): void {
        director.loadScene("main_game");
    }

    loadAboutScene(): void {
        director.loadScene("about_game");
    }

    backToMainMenu(): void {
        director.loadScene("main_menu");
    }
    //#endregion
}

I want to attach the corresponding node from the current scene right in the script. And I got “[Preview] Cannot read property ‘on’ of null”. How can I fix this?

Likely it cannot find one of the buttons, if you want your buttons to stay on screen without duplicate them in all the scenes, you should be using persist node
https://docs.cocos.com/creator/manual/en/scripting/scene-managing.html#scene-resource-management-and-persistent-nodes

1 Like

thanks :heart: