unity3d - 脚本运行时统一崩溃

标签 unity3d crash udp unityscript

在我简单的usp服务器查找器脚本中,当我选择客户端时,它会导致统一崩溃,而我找不到原因;

import System.Net.Sockets;

private var udp_server:UdpClient;
private var udp_client:UdpClient;
private var udp_port:int = 18000;
private var udp_broadcast_ip:IPAddress = IPAddress.Parse ("224.0.0.224");

private var udp_received_message:String;
private var udp_endpoint:IPEndPoint;

private var selected:boolean = false;
private var clientStarted:boolean = false;

function StartServer(){

    udp_server = new UdpClient(udp_port, AddressFamily.InterNetwork);

    udp_server.JoinMulticastGroup(udp_broadcast_ip);
    udp_endpoint = new IPEndPoint(udp_broadcast_ip, udp_port);

    InvokeRepeating("StartBroadcastUDP", 0.0,0.3);
}

function StartClient(){
    udp_client = new UdpClient();

    udp_endpoint = new IPEndPoint(IPAddress.Any, udp_port);
    udp_client.Client.Bind(udp_endpoint);

    udp_client.JoinMulticastGroup(udp_broadcast_ip);

    /*
    while(true){
        yield;
        var udp_received_message_byte:byte[] = udp_client.Receive(udp_endpoint);
        udp_received_message = Encoding.Unicode.GetString(udp_received_message_byte);
        print("Received Message: " + udp_received_message);
    }*/

    clientStarted = true;

}

function StartBroadcastUDP(){
    var udp_broadcast_message = Encoding.Unicode.GetBytes("GAME SERVER");

    if(udp_broadcast_message != ""){

        udp_server.Send(udp_broadcast_message, udp_broadcast_message.Length);
    }
}

function OnGUI(){
    if(!selected){
        if(GUI.Button(Rect(0, 0, 100, 100), "Server")){
            StartServer();
            selected = true;
        }else if(GUI.Button(Rect(100, 0, 100, 100), "Client")){
            StartClient();
            selected = true;
        }
    }
}

function Update(){
    /*
    if(clientStarted){
        var udp_received_message_byte:byte[] = udp_client.Receive(udp_endpoint);
        udp_received_message = Encoding.Unicode.GetString(udp_received_message_byte);
        print("Received Message: " + udp_received_message);
    }*/
}

我尝试在两个注释的部分中执行此操作,在开始时我先将其保持在相同的功能中,但是它崩溃了,所以我将其移动到了更新功能中,但仍然崩溃。帮帮我?

最佳答案

while(true)中的StartClient()确实会使冻结编辑器/应用程序,因为StartClient()没有被称为协程,因此yield不会返回到Unity引擎,并且您的程序会永久卡住。

因此,还有另一件事。看来udp-client.Receive是一个同步调用,这意味着它正在阻塞等待数据包的代码。除非您每秒有60个数据包,否则游戏确实会冻结。

关于unity3d - 脚本运行时统一崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29889182/

相关文章:

c# - HoloLens -- 在 Unity 中拍摄照片并保存到磁盘

iOS objc_msgSend 崩溃,没有报告或警告

c++ - 将 UDP 数据包发送到同一地址的效率

networking - 可靠的udp广播库?

error-handling - 处理错误代码

ios - 为什么更新到 Xcode 12 后会出现链接错误?

c# - unity Texture2D loadImage 精确取值

iOS崩溃: Tapping the globe in keyboard to go to the emoji keyboard causes crash

ios - 如何解决按下按钮时出现 "class is not key value coding-compliant"错误?

networking - TCP 如何分段其数据