Unity、C#、SocketIO:变量、objects、callback/action 中无法访问的方法

Unity, C#, SocketIO: variables, objects, methods not accessible in callback/action

如标题所示,我无法在 socker.io 的回调操作中访问某些 variables/objects 及其方法。 这是我的代码来说明问题:

using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using SocketIOClient;

public class SimulationManager : MonoBehaviour
{

    [Header("References")]
    [SerializeField] private GameObject robot;
    private MovementController movement;
    private SensorController sensors;

    [Header("Setup")]
    [SerializeField] private string serverIP;
    [SerializeField] private string serverPort;

    private SocketIO socket;


    // Start is called before the first frame update
    private void Start()
    {
        movement = robot.GetComponent<MovementController>();
        sensors = robot.GetComponent<SensorController>();

        InitSockets();
    }

    private void InitSockets()
    {
        string address = string.Format("http://{0}:{1}", serverIP, serverPort);
        socket = new SocketIO(address);

        // standard connection and error events
        socket.OnConnected += (sender, e) => {
            Debug.Log("socket connected");

            // register to server as simulation
            socket.EmitAsync("register", "simulation");
        };

        socket.OnDisconnected += (sender, e) => Debug.Log("socket disconnected");
        socket.OnError += (sender, e) => Debug.Log("socket error: " + e);
        
        // handle receiving commands
        Action<SocketIOResponse> callback = OnCommandReceived;
        socket.On("command", callback);

        socket.ConnectAsync();
    }

    private void OnCommandReceived(SocketIOResponse command)
    {
        string type = command.GetValue<string>(0);
        float parameter = float.Parse(command.GetValue<string>(1));

        Debug.Log(string.Format("command received: {0} {1}", type, parameter));
        movement.Rotate(90f);
    }

}

OnCommandReceived 中,我正在尝试访问之前声明的 movement-object 并调用它的方法 Rotate(...)。 object 似乎不是 null,因为它在尝试访问它时不会在统一控制台中显示任何错误,也不会导致游戏崩溃。输出接收到的命令的 Debug.Log(...) 工作得很好。将字符串声明为我的 class 的 属性 并以这种方式输出它也是可能的。就在我将运动或传感器 objects 引入 Debug.Log(...) 后,它从未出现在控制台中,而且正如我之前所说,奇怪地没有任何错误。

从 class 中的其他上下文访问所需的 variables/methods/properties 没有问题。

此外,我没有忘记在 unity 编辑器中设置对 robot-object 的引用,所以不用担心。这至少也会在控制台中给我一条错误消息。

我现在能够解决问题了。问题是

  1. SocketIO 库捕获了所有发生的异常,但没有在控制台中输出任何内容。我只需要在 try-catch 中包围我的方法调用,看看哪里出了问题。 和
  2. unity 不是线程安全的,因此您不能从主线程以外的任何线程调用方法。

有关如何解决此问题的更多详细信息,请参见 in a reddit post here