UnityPyBridge is a lightweight and modular TCP-based bridge that allows real-time communication between Python scripts and Unity software. It allows external systems—such as simulations, control scripts, or digital twins—to send structured data to Unity and dynamically manipulate objects within a scene.
The Unity side of the bridge consists of a lightweight TCP listener implemented as a MonoBehaviour component. Once attached to a GameObject within a Unity scene, it listens for incoming JSON messages on a configurable port.
Upon receiving a message, the script parses it and updates the position of matching GameObjects in the scene, using their names as unique identifiers. The core behavior of the listener can be extended or customized by modifying the HandleMessage(string json)
method, which is responsible for interpreting incoming messages and managing the state of the scene accordingly.
Example of a valid JSON message sent to Unity:
{ "type": "position", "id": "Cube_01", "data": [1.0, 0.0, -1.0] }
This would move the GameObject named Cube_01
to the specified 3D coordinates in real-time.
The Python side acts as the external client that establishes a TCP connection with the Unity listener. Once connected, it can send structured messages to update Unity GameObjects. The client serializes messages into JSON, transmits them over the socket, and optionally parses the response from Unity.
The provided Python script demonstrates a simple usage pattern, in which two GameObjects are moved dynamically by sending updated positions every few milliseconds.
By editing or extending the send_message()
method and the main loop, developers can adapt the client to a wide variety of use cases.
Follow these steps to set up and run UnityPyBridge:
- Create a New Unity Project
- Open Unity and create a new project. Name it as desired (e.g., UnityPyBridgeDemo).
- Import the Listener Script
- Within your Unity project, navigate to the Assets folder.
- Create a new folder named Scripts and copy the UnityListener.cs file into it.
- Prepare the Scene
- In the Hierarchy, create two Cube GameObjects.
- Rename one to Cube_01 and the other to Cube_02.
- Attach the Listener Component
- Attach the UnityListener.cs component to both cubes. (Alternatively, for centralized control, you may attach UnityListener.cs to an empty GameObject instead.)
- Run the Unity Project
- Save your scene and press the Play button. The Unity listener will start on port 25001 and wait for incoming messages.
- Start the Python Client
-
In a terminal, navigate to the directory containing the PythonClient.py file and run:
python PythonClient.py
The Python script will send JSON-formatted position updates to Unity, which will update the corresponding cubes in real time.
This project is licensed under the MIT License.
You are free to use, modify, and distribute it for both personal and commercial purposes, provided that proper attribution is given.