Python发送数据到Unity实现

Unity设置:

  • 打开Unity项目。
  • 创建一个空的GameObject,并附加一个新的脚本TCPReceiver
复制代码
  using System.Net;
  using System.Net.Sockets;
  using System.Text;
  using UnityEngine;
  using System.Threading;

  public class MyListener : MonoBehaviour
  {
      Thread thread;
      public int connectionPort = 25001;
      TcpListener server;
      TcpClient client;
      bool running;


      void Start()
      {
          // Receive on a separate thread so Unity doesn't freeze waiting for data
          ThreadStart ts = new ThreadStart(GetData);
          thread = new Thread(ts);
          thread.Start();
      }

      void GetData()
      {
          // Create the server
          server = new TcpListener(IPAddress.Any, connectionPort);
          server.Start();

          // Create a client to get the data stream
          client = server.AcceptTcpClient();

          // Start listening
          running = true;
          while (running)
          {
              Connection();
          }
          server.Stop();
      }

      void Connection()
      {
          // Read data from the network stream
          NetworkStream nwStream = client.GetStream();
          byte[] buffer = new byte[client.ReceiveBufferSize];
          int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

          // Decode the bytes into a string
          string dataReceived = Encoding.UTF8.GetString(buffer, 0, bytesRead);
          
          // Make sure we're not getting an empty string
          //dataReceived.Trim();
          if (dataReceived != null && dataReceived != "")
          {
              // Convert the received string of data to the format we are using
              position = ParseData(dataReceived);
              nwStream.Write(buffer, 0, bytesRead);
          }
      }

      // Use-case specific function, need to re-write this to interpret whatever data is being sent
      public static Vector3 ParseData(string dataString)
      {
          Debug.Log(dataString);
          // Remove the parentheses
          if (dataString.StartsWith("(") && dataString.EndsWith(")"))
          {
              dataString = dataString.Substring(1, dataString.Length - 2);
          }

          // Split the elements into an array
          string[] stringArray = dataString.Split(',');

          // Store as a Vector3
          Vector3 result = new Vector3(
              float.Parse(stringArray[0]),
              float.Parse(stringArray[1]),
              float.Parse(stringArray[2]));

          return result;
      }

      // Position is the data being received in this example
      Vector3 position = Vector3.zero;

      void Update()
      {
          // Set this object's position in the scene according to the position received
          transform.position = position;
      }
  }

Python设置:

  • 如果尚未安装socket库,安装(pip install socket

  • 创建一个Python脚本send_data.py

    复制代码
    import socket
    
    host, port = "127.0.0.1", 25001
    data = "1,2,3"
    
    # SOCK_STREAM means TCP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    try:
        # Connect to the server and send the data
        sock.connect((host, port))
        sock.sendall(data.encode("utf-8"))
        response = sock.recv(1024).decode("utf-8")
        print (response)
    
    finally:
        sock.close()
相关推荐
点心的游戏开发世界2 小时前
GDScript 入门笔记:目录
开发语言·笔记·游戏引擎·godot
XR技术研习社2 小时前
关于 PICO 串流测试中报错 IndexOutOfRangeException: renderPassIndex 的两个排障方法
unity·ar·xr·vr
想做后端的前端2 小时前
Unity · 性能优化:内存管理完全指南:从托管堆到跨桥开销
unity·性能优化·游戏引擎
平行云5 小时前
实时云渲染信创架构解析:从GPU池化到全栈适配的技术演进
linux·unity·docker·ue5·webgl·数字孪生·实时云渲染
玖玥拾7 小时前
Lua 基础语法(五)Unity xLua基础配置与 C# 访问 Lua
开发语言·unity·c#·lua
玖玥拾1 天前
Lua 基础语法(二)
开发语言·unity·lua
点心的游戏开发世界1 天前
GDScript 入门笔记(十六):文件读写与数据持久化
开发语言·笔记·游戏引擎·godot
点心的游戏开发世界1 天前
GDScript 入门笔记(十三):字符串操作
开发语言·笔记·游戏引擎·godot
点心的游戏开发世界1 天前
GDScript 入门笔记(十二):类型系统进阶
笔记·游戏引擎·godot
玖玥拾1 天前
Lua 基础语法(三) 元表 metatable、元方法、模拟面向对象
开发语言·unity·lua