Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 尝试捕获未在Unity中执行的代码块_C#_Visual Studio_Unity3d - Fatal编程技术网

C# 尝试捕获未在Unity中执行的代码块

C# 尝试捕获未在Unity中执行的代码块,c#,visual-studio,unity3d,C#,Visual Studio,Unity3d,在一个多人游戏项目中,我有一个try-catch语句,用于检查Unity中通过UDP的连接状态。它在try代码块中接收来自服务器的回调,catch代码块用于在连接突然中断时获取异常。我的问题是catch块没有执行我用来通知用户与服务器的连接已断开的代码。它似乎只执行与异常相关的代码,比如Debug.error //Callback from server connection private void ConnectCallback(IAsyncResult _result) {

在一个多人游戏项目中,我有一个try-catch语句,用于检查Unity中通过UDP的连接状态。它在try代码块中接收来自服务器的回调,catch代码块用于在连接突然中断时获取异常。我的问题是catch块没有执行我用来通知用户与服务器的连接已断开的代码。它似乎只执行与异常相关的代码,比如Debug.error

//Callback from server connection
        private void ConnectCallback(IAsyncResult _result) {
            try {
                //Ends connection
                socket.EndConnect(_result);
            } catch (Exception e) {
                
               //These three lines are the problem. They won't execute
                UIManager.instance.logPanel.enabled = true;
                UIManager.instance.logPanel.text = "Servidor no disponible";
                UIManager.instance.HideUsernameSelection();
            }

            //If theres no connection to the server the function returns
            if (!socket.Connected) 
            {
                return;
            }

            //Reference to data stream
            stream = socket.GetStream();

            //Packet for data received from server
            receivedData = new Packet();

            //Read
            stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
        }

是否有强制catch块执行其中的代码的方法?

可以肯定的是,这个调用是异步的,所以在不同的线程/任务上

大多数Unity API只能在Unity主线程上使用。唯一的例外是基本上所有的纯数学结构,它们不直接影响或依赖于场景

大多数情况下,这是通过所谓的主线程调度程序解决的。它看起来有点像

public class MainThreadDispatcher : MonoBehaviour
{
    #region Singleton Pattern
    private static MainThreadDispatcher _instance;

    public static MainThreadDispatcher Instance
    {
        get
        {
            if(_instance) return _instance;

            _instance = FindObjectOfType<MainThreadDispatcher>();
            
            if(_instance) return _instance;

            _instance = new GameObject(nameof (MainThreadDispatcher)).AddComponent<MainThreadDispatcher>();
        }  
    }

    private void Awake ()
    {
        if(_instance && _instance != this)
        {
            Destroy (gameObject);
            return;
        }

        _instance = this;
        DontDestroyOnLoad(gameObject);
    }
    #endregion

    #region Dispatcher
    private readonly Queue<Action> _actions = new Queue<Action>();

    private void LateUpdate ()
    {
        lock (_actions)
        {
            while(_actions.Count > 0)
            {
                var action = _actions.Dequeue();

                action?.Invoke();
            }
        }
    }

    public void DoInMainThread(Action action)
    {
        lock(_actions)
        {
            _actions.Enqueue(action);
        }
    }
    #endregion
}
try
{
    //Ends connection
    socket.EndConnect(_result);
} 
catch (Exception e) 
{
    MainThreadDispatcher.Instance.DoInMainThread(() =>
    {
        // To have the information is always helpful I'd say ;)
        Debug.LogWarning($"{e.GetType()} - {e.Message}/n{e.StackTrace}");
        UIManager.instance.logPanel.enabled = true;
        UIManager.instance.logPanel.text = "Servidor no disponible";
        UIManager.instance.HideUsernameSelection();
    }
}

根据代码和MS文档中的注释,socket.EndConnect似乎正在结束连接。我在try中没有看到任何connect方法,所以为什么希望捕获错误?对不起,我没有复制整个函数。我刚刚更新了它。我想要的是,如果连接到服务器的回调为负,则执行UIManager中的函数,这样我就可以显示重新连接的UI和服务器错误。是的,它成功了!非常感谢@alex2furious,我很高兴听到您的问题已经解决,您可以点击'✔' 以适当的答复作为答复。它还将帮助其他人解决类似问题。