Python to Unity Data Transfer

Python to Unity Data Transfer

Python to Unity Data Transfer

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

 

Python Code

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()

 

Unity Code

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()
    {
        // Create a new UDP client
        udpClient = new UdpClient(port);

        // Set the endpoint to any IP address and port 0
        endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
    }

    private void Update()
    {
        // Check if there is any data available
        if (udpClient.Available > 0)
        {
            // Receive the data and endpoint of the sender
            byte[] data = udpClient.Receive(ref endPoint);

            // Convert the data to a string
            string message = Encoding.ASCII.GetString(data);

            // Print the message to the console
            Debug.Log("Received message: " + message);
        }
    }

    private void OnDestroy()
    {
        // Close the UDP client when the object is destroyed
        udpClient.Close();
    }
}