【问题标题】:unity crashes when script runs脚本运行时统一崩溃
【发布时间】:2023-03-15 07:20:01
【问题描述】:

在我简单的 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 将其保持在相同的功能中但它崩溃了,所以我将它移动到更新函数中但它仍然崩溃。帮忙?

【问题讨论】:

  • 如果注释掉的代码不是重现错误所必需的,为什么还要发布呢?如果您只留下可以重现问题的最少量代码,则更容易定位问题。
  • 另外,“崩溃”到底是什么意思?
  • 评论代码是导致崩溃的原因;当我取消注释 StartClient 函数中的 while 循环时,它崩溃了,所以起初我虽然是 while 循环导致它崩溃,所以我评论了它并在更新函数中再次写了它,所以当我说 clientstarted 在 startclient() 中为真时更新功能将运行代码,但这也会导致它崩溃,所以我无法猜测是什么导致它崩溃(当我的意思是崩溃时,我的意思是在 Windows 中使编辑器没有响应并最终自行关闭,而在 android 上只需关闭应用程序) .如果这里有帮助的话,还有日志文件 - pastebin.com/JZ1kY62a

标签: unity3d crash udp unityscript


【解决方案1】:

while(true)in StartClient() 确实会让编辑器/应用程序被冻结,因为StartClient() 不是作为协程调用的,所以yield 不会返回Unity 引擎,你的程序会永远卡在一会儿。

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

【讨论】:

    猜你喜欢
    • 2017-05-01
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多