Ali Şahan Yalçın

Python to Unity Data Transfer

·2 min read
PythonUnityNetworking
Python to Unity Data Transfer

This example shows how to send data from Python to Unity using UDP.

The Python script sends a message to the Unity application, which receives the message and prints it to the console.

main.py

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import socket

# Set up a UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Define the address and port of the recipient
host = '127.0.0.1'
port = 5066
address = (host, port)

# Define the data to be sent
data = b'Hello, world!'

# Send the data
sock.sendto(data, address)

# Close the socket
sock.close()

UdpServer.cs

csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;

public class UdpServer : MonoBehaviour
{
    [SerializeField] private int port = 5066;
    [SerializeField] private string ipAddress = "127.0.0.1";

    private UdpClient udpClient;
    private IPEndPoint endPoint;

    private void Start()
    {
        udpClient = new UdpClient(port);
        endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
    }

    private void Update()
    {
        if (udpClient.Available > 0)
        {
            byte[] data = udpClient.Receive(ref endPoint);
            string message = Encoding.ASCII.GetString(data);
            Debug.Log("Received message: " + message);
        }
    }

    private void OnDestroy()
    {
        udpClient.Close();
    }
}

Videos

Video
0:00
0:00

This video not a successful one, but it is a good example of what can we do with this method.

Video
0:00
0:00

This video not a successful one either 🤷‍♂️

Video
0:00
0:00

This is close to a successful one 🎉