Keep connection with Colyseus server when changing scene

Hi,
I am trying to stay connected with Colyseus Server while switching the scenes. I’ve added Persist Root Node for node with my typescript component.

game.addPersistRootNode(this.node);

But my question is how to move client and room objects from one script to script in new scene?

Eventually I can reconnect to the room but I would like to keep the same user client and don’t have to connect to the server again. How can I do that?

My code is from: Cocos Creator - Colyseus 0.14

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

import Colyseus from 'db://colyseus-sdk/colyseus.js';

@ccclass('NetworkManager')
export class NetworkManager extends Component {
    @property hostname = "localhost";
    @property port = 2567;
    @property useSSL = false;

    client!: Colyseus.Client;
    room!: Colyseus.Room;

    start () {
        // Instantiate Colyseus Client
        // connects into (ws|wss)://hostname[:port]
        this.client = new Colyseus.Client(`${this.useSSL ? "wss" : "ws"}://${this.hostname}${([443, 80].includes(this.port) || this.useSSL) ? "" : `:${this.port}`}`);

        // Connect into the room
        this.connect();
    }

    async connect() { 
        try {
            this.room = await this.client.joinOrCreate("my_room");

            console.log("joined successfully!");
            console.log("user's sessionId:", this.room.sessionId);

            this.room.onStateChange((state) => {
                console.log("onStateChange: ", state);
            });

            this.room.onLeave((code) => {
                console.log("onLeave:", code);
            });

        } catch (e) {
            console.error(e);
        }
    }
}

i would recommend you create a singleton instance that just keeps track of your networking stuff and you should be able to use it across the scenes without issues.

in one script you can create a TS class for NetworkManager
export const networkmanager = new NetworkManager()

in the scripts where you want to use it just do
import { networkmanager } from "./NetworkManager";

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.