python数据实时传给unity工程并绘制出来

python

# 服务器端代码
import socket
import random
import struct
import time

# 创建一个服务器Socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 监听的地址和端口
host = '127.0.0.1'
port = 12345

# 绑定地址和端口
server_socket.bind((host, port))

# 开始监听连接
server_socket.listen(1)

# 等待客户端连接
client_socket, addr = server_socket.accept()
print('连接来自:', addr)

try:
    # 发送和接收数据
    while True:
        data = client_socket.recv(1024).decode('utf-8')
        if not data:
            break
        print('接收到数据:', data)
        # client_socket.sendall('已收到数据'.encode('utf-8'))

        time.sleep(0.5)


        distance = random.uniform(0, 1)
        # distance = 3.1415926
        print(distance)
        strs = "Elegance is the only beauty that never fades."
        dis = "the distance is %.3f meters. " % distance
        # client_socket.send(dis.encode('utf-8') + b'\n' + strs.encode('utf-8'))

        bytes_value = struct.pack("d", distance)  # Big-endian format
        client_socket.send(bytes_value)
        print('已发送数据:', dis)
except ConnectionResetError:
    print("Unity客户端关闭连接")
finally:
    # 关闭连接
    client_socket.close()
    server_socket.close()

unity3d

RecvData.cs

// Unity 3D客户端代码
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;

public class RecvData : MonoBehaviour
{
    // 服务器地址和端口
    private string serverAddress = "127.0.0.1";
    private int port = 12345;

    // 与服务器的连接
    private TcpClient client;
    private NetworkStream stream;
    private bool isConnect = false;
    byte[] receiveBuffer = new byte[1024];
    public static double dis_value = -1.0f;

    // Start is called before the first frame update
    void Start()
    {
        // 连接到服务器
        ConnectToServer();


    }

    // Update is called once per frame
    void Update()
    {
        if(isConnect)
        {
            SendDataToServer("Hello Server");
            Debug.Log(ReceiveDataFromServer());            ;

        }

    }
    // 连接到服务器
    private void ConnectToServer()
    {
        try
        {
            client = new TcpClient(serverAddress, port);
            stream = client.GetStream();
            isConnect = true;

            Debug.Log("成功连接到服务器");
        }
        catch (Exception e)
        {
            Debug.Log("无法连接到服务器:" + e);
        }
    }

    // 发送数据到服务器
    public void SendDataToServer(string data)
    {
        if (stream != null)
        {
            byte[] byteData = Encoding.UTF8.GetBytes(data);
            stream.Write(byteData, 0, byteData.Length);
            Debug.Log("已发送数据到服务器:" + data);
        }
        else
        {
            Debug.Log("无法发送数据,连接未建立");
        }
    }

    // 从服务器接收数据
    public string ReceiveDataFromServer()
    {
        try
        {
            int bytesRead = stream.Read(receiveBuffer, 0, receiveBuffer.Length);
            //Debug.Log("bytesRead is " + bytesRead);
             dis_value = BitConverter.ToDouble(receiveBuffer, 0);
            print("dis_value is " + dis_value);
            return dis_value.ToString();
        }
        catch (Exception e)
        {
            Debug.Log("接收数据时发生异常:" + e);
            return null;
        }


    }

    // 关闭连接
    private void OnApplicationQuit()
    {
        if (stream != null)
        {
            stream.Close();
        }
        if (client != null)
        {
            client.Close();
        }
    }
}

需要导入xchart绘图package

ValueChat.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using XCharts.Runtime;

public class ValueChat : MonoBehaviour
{
    public double distance_gap = 0.0f;
    LineChart gap_chart = null;

    private float timeBetweenGenerations = 0.01f; // 两次生成之间的时间间隔
    private bool isShow = false; // 标记当前是否正在生成物体

    public Text gapValue_text;
    // Start is called before the first frame update
    void Start()
    {

        SetValue_Show();
        StartCoroutine("ShowData"); // 调用协程函数


    }

    // Update is called once per frame
    void Update()
    {
        if (RecvData.dis_value != -1.0f)
        {
            //distance_gap = double.Parse(HelloRequester.gap_value);
            distance_gap = RecvData.dis_value;

            string formattedNumber = distance_gap.ToString("0.000");
            gapValue_text.text = "The gap value is " + formattedNumber + " mm";
        }
        //distance_gap = double.Parse(HelloRequester.gap_value);

    }

    IEnumerator ShowData()
    {
        while (true)
        {

            if (!isShow)
            {
                yield return new WaitForSeconds(timeBetweenGenerations); // 等待指定的时间间隔后再进行下一次生成
 
                Show_Line(gap_chart);
                isShow = true; // 设置为正在生成状态
            }
            else
            {
                yield return null; // 不进行任何操作直到下一次生成
                isShow = false; // 设置为正在生成状态

            }
        }
    }


        void SetValue_Show()
    {
        var chart = gameObject.GetComponent<LineChart>();

        if (chart == null)
        {
            chart = gameObject.AddComponent<LineChart>();
            chart.Init();
        }
        gap_chart = chart;

        //设置标题:
        var title = chart.EnsureChartComponent<Title>();
        title.text = "Gap Value Line";

        //设置提示框和图例是否显示:
        var tooltip = chart.EnsureChartComponent<Tooltip>();
        tooltip.show = true;

        var legend = chart.EnsureChartComponent<Legend>();
        legend.show = false;

        //设置坐标轴:
        var xAxis = chart.EnsureChartComponent<XAxis>();
        xAxis.splitNumber = 10;
        xAxis.boundaryGap = true;
        xAxis.type = Axis.AxisType.Category;

        var yAxis = chart.EnsureChartComponent<YAxis>();
        yAxis.type = Axis.AxisType.Value;


        //清空默认数据,添加Line类型的Serie用于接收数据:

        chart.RemoveData();
        chart.AddSerie<Line>("line");

        添加10个数据:
        //for (int i = 0,  j = 1 ; i<60 ; i = i + 5, j++)
        //    {
        //        chart.AddXAxisData("T " + j);
        //    //chart.AddData(0, Random.Range(10, 20));
        //    chart.AddData(0, distance_gap);
        //    Debug.Log("-----------" + distance_gap);
        //    }
    }

    void Show_Line(LineChart _gap)
    {
        _gap.AddData(0, distance_gap);

    }
}

运行

修改图的坐标和平均数显示的小数点后位数。

相关推荐

最近更新

  1. leetcode705-Design HashSet

    2024-04-02 14:26:05       5 阅读
  2. Unity发布webgl之后打开streamingAssets中的html文件

    2024-04-02 14:26:05       5 阅读
  3. vue3、vue2中nextTick源码解析

    2024-04-02 14:26:05       6 阅读
  4. 高级IO——React服务器简单实现

    2024-04-02 14:26:05       5 阅读
  5. 将图片数据转换为张量(Go并发处理)

    2024-04-02 14:26:05       4 阅读
  6. go第三方库go.uber.org介绍

    2024-04-02 14:26:05       6 阅读
  7. 前后端AES对称加密 前端TS 后端Go

    2024-04-02 14:26:05       7 阅读

热门阅读

  1. CPU狂飙900%,该怎么处理

    2024-04-02 14:26:05       3 阅读
  2. 【OpenCV进阶】图像中添加中文字幕

    2024-04-02 14:26:05       5 阅读
  3. 低代码与系统集成:革新企业应用开发的新动力

    2024-04-02 14:26:05       3 阅读
  4. MYSQL08_页的概述、内部结构、行格式

    2024-04-02 14:26:05       3 阅读
  5. 面试中的MVCC到底是什么意思?

    2024-04-02 14:26:05       3 阅读
  6. Spring与SpringMVC常用注解

    2024-04-02 14:26:05       5 阅读
  7. elasticsearch之多条件查询

    2024-04-02 14:26:05       4 阅读
  8. Redis

    Redis

    2024-04-02 14:26:05      2 阅读
  9. 递归---算法

    2024-04-02 14:26:05       5 阅读
  10. 2024最新华为OD机试试题库全 -【符号运算】- C卷

    2024-04-02 14:26:05       3 阅读