首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >脚本运行时unity崩溃

脚本运行时unity崩溃
EN

Stack Overflow用户
提问于 2015-04-27 15:00:52
回答 1查看 367关注 0票数 1

在我的简单的usp服务器查找器脚本中,当我选择客户端时,它使unity崩溃,并且我找不到原因;

代码语言:javascript
复制
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将它保存在相同的函数中,但它崩溃了,所以我把它移到了update函数中,但它仍然崩溃了。帮助?

EN

回答 1

Stack Overflow用户

发布于 2015-04-27 20:13:24

StartClient()中的while(true)确实会使编辑器/应用程序冻结,因为StartClient()不是作为协程调用的,所以yield不会返回到Unity引擎,并且您的程序将永远停留在一段时间内。

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29889182

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档