Sending realtime gameobject position via websockets to a website

29 views Asked by At

For a research application we need to send the realtime position data of a unity gameobject using a websocket server to a dashboard where the positions can be tracked. We use WebsocketSharp and Singletons to collect the data, and the websocket classes look like this:

using UnityEngine;
using System;
using WebSocketSharp;
using WebSocketSharp.Server;
using UnityEditor;
using System.Threading;
using TMPro;

public class ServerBehaviour : MonoBehaviour
{
    private static ServerBehaviour instance;
    [SerializeField] public GameObject cube;
    
    private ServerBehaviour()
    {
        
    }
    
    void Start()
    {
        var wssv = new WebSocketServer(System.Net.IPAddress.Loopback, 7777);

        wssv.KeepClean = true;

        wssv.AddWebSocketService<SendData>("/SendData");
        wssv.Start();

        if (!EditorApplication.isPlaying && EditorApplication.isPlayingOrWillChangePlaymode)
        {
            wssv.Stop();
        }
    }

    void Update()
    {
Debug.Log(ServerBehaviour.Instance.GetCubeYPosition())
    }

    public static ServerBehaviour Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new ServerBehaviour();
            }
            return instance;
        }
    }
      public float GetCubeYPosition()
    {
        if (cube != null)
        {
            return cube.transform.position.y;
        }
        else
        {
            Debug.LogWarning("Cube is not set!");
            return 0f; // or any default value
        }
    }
}

public class SendData : WebSocketBehavior
{
    private bool wait = false;

    protected override void OnOpen()
    {
        SendToClient();
    }

    void SendToClient()
    {
        while (true)
        {
            float cubeYPosition = ServerBehaviour.Instance.GetCubeYPosition();
            Debug.Log(cubeYPosition);
            string dataStr = cubeYPosition.ToString();
            Debug.Log(dataStr);
            Send(dataStr);

            Thread waiter = new Thread(new ThreadStart(Wait));
            waiter.Start();

            while (wait == true)
            {
                // Do nothing
            }
        }
    }

    void Wait()
    {
        wait = true;
        Thread.Sleep(100);
        wait = false;
    }
}

When starting unity the server will connect with the dashboard, log the data to the unity console on every update, however it won't send any data nor will it continue the while loop in SendToClient.

We tried multiple solutions expecting to receive the data in the WebsocketBehaviour class, however nothing works. We think it is because the class does not inherit from MonoBehaviour, but we don't know how to work around this. If anyone could help us they would be heroes!

0

There are 0 answers