繁体   English   中英

c# unity IEnumerator 在事件处理程序中不起作用

[英]c# unity IEnumerator not working in eventhandler

ConnectToWebSocket() 正在工作,但是当我尝试触发 tryConnectToWebSocket() 时,当我运行时它不起作用,当我关闭服务器时,我得到了这个日志(ws://localhost:8080/user),我得到了这些日志(你失去了连接) 和 (false) 但我在控制台上看不到“来自 while 循环外部的这条消息”和“来自 while 循环内部的这条消息”。 所以我的 IEnumerator tryConnectToWebSocket() 不起作用。

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using WebSocketSharp;

public class websocks : MonoBehaviour
{

public static WebSocket ws = new WebSocketSharp.WebSocket("ws://localhost:8080/user");
public static bool stop;
public delegate void MyDelegate(string num);
public static MyDelegate myDelegate;

private void Awake()
{
    stop = false;
    StartCoroutine(ConnectToWebSocket());
    
}
private IEnumerator ConnectToWebSocket()
{
    ws.Connect();
    ws.OnMessage += (sender, e) => myDelegate(e.Data);
    if (ws == null)
    {
        Debug.Log("coudn't connect");
        
    }
    else
    {
        Debug.Log(ws.Url);
        
    }

    yield return new WaitForSeconds(0.05f);
   
}


// Start is called before the first frame update
void Start()
{
    websocks.ws.OnClose += (sender, e) =>
    {

        Debug.Log("you losted connection");
        Debug.Log(ws.IsAlive);
        
        stop = true;
        StartCoroutine(tryConnectToWebSocket());

    };
   
}

// Update is called once per frame
void Update()
{


}

public IEnumerator tryConnectToWebSocket()
{
    Debug.Log("this message from outside of while loop");

    while (ws.IsAlive == false)
    {
        Debug.Log("this message from inside while loop");
        yield return new WaitForSeconds(5f);
        ws.Connect();
    }
    if (ws.IsAlive == true)
    {
        Debug.Log("connected");
        stop = false;
    }
    yield return null;
}

}

你的问题是线程。 大多数 Unity ApI 可能只被 Unity 主线程使用。

OnCloseOnMessage等事件很可能在后台线程上调用。

您可以使用主线程调度程序模式,例如

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using WebSocketSharp;

public class websocks : MonoBehaviour
{
    public static WebSocket ws = new WebSocketSharp.WebSocket("ws://localhost:8080/user");
    public static bool stop;
    public delegate void MyDelegate(string num);
    public static MyDelegate myDelegate;

    // Thread-safe Queue (first-in first-out)
    private readonly ConcurrentQueue<Action> _actions = new ConcurrentQueue<Action>();

    private void Awake()
    {
        stop = false; 
    }

    private void Start ()
    {
        // Enqueue to the actions so it will be executed in the main thread
        ws.OnMessage += (sender, e) => _actions.Enqueue(() => myDelegate(e.Data));

        websocks.ws.OnClose += (sender, e) =>
        {
            _actions.Enqueue(() => 
            {
                Debug.Log("you losted connection");
                Debug.Log(ws.IsAlive);
        
                stop = true;
                StartCoroutinee(tryConnectToWebSocket());
            });
        };

        StartCoroutine(ConnectToWebSocket())
    }

    private void Update ()
    {
        // Work the actions off in the Unity main thread
        while(_actions.TryDequeue(out var action)
        {
            action?.Invoke();
        }
    }

    private IEnumerator ConnectToWebSocket()
    {
        if (ws == null)
        {
            Debug.Log("coudn't connect");  
            yield break;      
        }
        else
        {
            Debug.Log(ws.Url);          
        }

        ws.Connect();

        // Waiting at the end of a Coroutine has absolutely no effect 
        // This should probably be a normal method instead
        yield return null;      
    }

    public IEnumerator tryConnectToWebSocket()
    {
        Debug.Log("this message from outside of while loop");
    
        while (ws.IsAlive == false)
        {
            Debug.Log("this message from inside while loop");
            yield return new WaitForSeconds(5f);
            ws.Connect();
        }
        if (ws.IsAlive == true)
        {
            Debug.Log("connected");
            stop = false;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM