itisnajim / SocketIOUnity

A Wrapper for socket.io-client-csharp to work with Unity.
MIT License
379 stars 65 forks source link

Scenemanager not working. #47

Open Hailiebaby16 opened 1 year ago

Hailiebaby16 commented 1 year ago
using System.Collections;
using System.Collections.Generic;
using SocketIOClient;
using SocketIOClient.Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UnityEngine;
using System;
using UnityEngine.SceneManagement;
public class NetworkManager : MonoBehaviour
{
    private string server = "http://localhost:3001";
    public static SocketIOUnity socket;
    // Start is called before the first frame update
    void Start()
    {
        socket = new SocketIOUnity(server, new SocketIOOptions
        {
            Query = new Dictionary<string, string>
                {
                    {"token", "UNITY" }
                }
            ,
            EIO = 4
            ,
            Transport = SocketIOClient.Transport.TransportProtocol.WebSocket
        });
        socket.JsonSerializer = new NewtonsoftJsonSerializer();
        socket.OnConnected += (sender, e) =>
        {
            Debug.Log("socket.OnConnected");
        };

        socket.OnPing += (sender, e) =>
        {
            Debug.Log("Ping");
        };
        socket.OnPong += (sender, e) =>
        {
            Debug.Log("Pong: " + e.TotalMilliseconds);
        };
        socket.OnDisconnected += (sender, e) =>
        {
            Debug.Log("disconnect: " + e);
        };
        socket.OnReconnectAttempt += (sender, e) =>
        {
            Debug.Log($"{DateTime.Now} Reconnecting: attempt = {e}");
        };
        ////

        Debug.Log("Connecting...");
        socket.Connect();

        socket.On("hello", (response) => {
            Debug.Log("Receive Hello");
            loadnewscene();
        });
    }

    public void loadnewscene()
    {
        Debug.Log("Changing Scene");
        SceneManager.LoadScene("GamePlay");
    }
    // Update is called once per frame

}
itisnajim commented 1 year ago

As I mentioned on https://github.com/itisnajim/SocketIOUnity#receiving

if you want to play with unity game objects (eg: rotating an object)
or saving data using PlayerPrefs system (or anything else like SceneManager.LoadScene) 
use OnUnityThread instead

To make your code work, do the following:

socket.OnUnityThread("hello", (response) =>
{
    Debug.Log("Receive Hello");
    loadnewscene();
});