Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

267
Visualizações
¿Cuál es la forma correcta de realizar operaciones relacionadas con la interfaz de usuario en Unity usando Socket IO?

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.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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); } } }); }); } }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda