- Home /
UdpClient.receive crashes unity
Been toying around with networking and I created a simple console application that can send messages over the internet but every time I've tried to bring what I made in my application always crashes unity.
using System.Collections;
using System.Collections.Generic;
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using UnityEngine;
public class networkHost : MonoBehaviour
{
public int port;
public IPEndPoint ipep;
public IPEndPoint sender;
public UdpClient newSock;
byte[] receiveData;
void Start()
{
receiveData = new byte[1024];
ipep = new IPEndPoint(IPAddress.Any, port);
newSock = new UdpClient(ipep);
sender = new IPEndPoint(IPAddress.Any, 0);
}
void Update()
{
if (Input.GetKeyDown("j"))
{
ReceiveData();
}
}
public void ReceiveData()
{
//This line crashes unity
receiveData = newSock.Receive(ref sender);
if (Encoding.ASCII.GetString(receiveData, 0, receiveData.Length) == "jump")
{
Jump(100);
}
}
public void Jump(int force)
{
GetComponent<Rigidbody>().AddForce(Vector3.up * force);
}
}
I really don't know why it crashes, especially because it exists and works almost identically in a console application. Some help would be appreciated the next thing I was gonna look at was threading but I really don't know.
Answer by Captaion · Sep 06, 2019 at 06:39 PM
Figured it out did more reading, udpclient.receive blocks until it receives a datagram which in unity's case means it crashes, so I put it inside an if check, that works. This is what I have now.
public class networkHost : MonoBehaviour
{
public string ip;
public IPAddress hostaddress;
public int port;
public IPEndPoint ipep;
public IPEndPoint sender;
public UdpClient newSock;
public Thread networkThread;
public byte[] receivedData;
public string dataString;
void Start()
{
networkThread = new Thread(ReceiveData);
networkThread.Start();
receivedData = new byte[0];
ipep = new IPEndPoint(IPAddress.Any, port);
newSock = new UdpClient(ipep);
sender = new IPEndPoint(IPAddress.Any, 0);
}
void Update()
{
ReceiveData();
}
public void ReceiveData()
{
if (newSock.Available > 0)
{
receivedData = newSock.Receive(ref sender);
dataString = Encoding.ASCII.GetString(receivedData);
if (Encoding.ASCII.GetString(receivedData) == "jump")
{
Jump(1000);
}
}
else
{
print("No data to receive");
}
}
public void Jump(int force)
{
GetComponent<Rigidbody>().AddForce(Vector3.up * force);
}
}
This code as it is now, works for me, I use a basic application outside of unity to send "jump" to my game. Although one thing I noticed for me was that the in editor player would not receive anything through the internet it had to be sent through LAN, and I honestly have no idea why, if anyone knows, cheers.
You may probably need WebSocket Solution ins$$anonymous$$d of UDP.
One of example: https://youtu.be/82_-a7WF3vs