He estado usando socket io durante algunos meses. Tuve muchos problemas con el socket mientras lo implementaba en Unity. Pero mi principal problema es que cuando recibo un mensaje/datos de una conexión de socket, no puedo simplemente llamar a un método para realizar algunas operaciones relacionadas con la interfaz de usuario. Lo que se me ocurrió para tener una variable booleana y hacer una operación específica cuando el bool es verdadero y realizar algo dentro de Update()
que creo que no es la forma eficiente de hacerlo.
Ejemplo:
public GameObject IdleGo; bool isDone = false; Socket socket; // Start is called before the first frame update void Start() { InitSocket(); } // Update is called once per frame void Update() { if(isDone) { isDone = false; IdleGo.SetActive(true); } } void InitSocket() { if (socket == null) { socket = IO.Socket(ServerURL); socket.On(Socket.EVENT_CONNECT, () => { Debug.Log("connecting.."); socket.On("response", (data) => { Debug.Log("response: " + data); if (data == "connected") { isDone = true; } }); }); } }
Me encantaría saber cómo se hace todo el proceso de socket con Unity, ya que también voy a hacer un juego multijugador en un futuro próximo.
Gracias.
Movería todo este asunto del socket a un subproceso de fondo para evitar cualquier bloqueo.
Para esperar el resultado en la Update
del hilo principal de Unity y un indicador bool
está bien, pero generalmente prefiero usar algo como
public GameObject IdleGo; private Socket socket; // A thread-safe queue for passing a callback into the next Update call private readonly ConcurrentQueue<Action> _mainThreadhActions = new ConcurrentQueue<Action>(); // Yes! You can make Start return IEnumerator // In this case Unity automatically starts it as a Coroutine instead private IEnumerator Start() { // Create a new thread in order to run the InitSocketThread method var thread = new Thread(InitSocketThread); // start the thread thread.Start(); // Wait until a callback action is added to the queue yield return new WaitUntil(() => _mainThreadhActions.Count > 0); // If this fails something is wrong ^^ // simply get the first added callback if(!_mainThreadhActions.TryDequeue(out var action)) { Debug.LogError("Whoops something went wrong!", this); yield break; } // Execute the code of the added callback action?.Invoke(); } void InitSocketThread() { if (socket == null) { socket = IO.Socket(ServerURL); socket.On(Socket.EVENT_CONNECT, () => { Debug.Log("connecting.."); socket.On("response", (data) => { // Simply wrap your main thread code by wrapping it in a lambda expression // which is enqueued to the thread-safe queue _mainThreadhActions.Enqueue(()=> { // This will be executed after the next Update call Debug.Log("response: " + data); if (data == "connected") { IdleGo.SetActive(true); } } }); }); } }