Unity 动画随着串口打开而变慢

问题描述 投票:0回答:1

我正在创建一个简单的统一程序,其中串行数据从 Arduino 发送并使用 C# 在 Unity 中进行处理。根据收到的值,播放两种不同的动画。

Arduino代码:

void setup() {
  Serial.begin(9600);
}

void loop() {
  int val=random(0,1);
  if(val==1){
    Serial.flush();
    Serial.println(1);
  }
  else{
    Serial.flush();
    Serial.println(0);
    }
  }
  delay(500);
}

Unity C# 代码:

using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.IO.Ports;
using UnityEngine;

public class ard : MonoBehaviour
{
    private SerialPort data_stream = new SerialPort("COM3", 9600);
    public GameObject kid;

    // Start is called before the first frame update
    void Start()
    {
        data_stream.Open();
    }

    // Update is called once per frame
    void Update()
    {
        if (data_stream.IsOpen) { 
            string val=data_stream.ReadLine();
            if (val == "0") {
                kid.GetComponent<Animator>().Play("Standing Idle To Fight Idle");
            }
            else if(val == "1")
            {
                kid.GetComponent<Animator>().Play("Fast Run");
            }
        }

    }
}

Arduino 发送数据,Unity 完美接收数据。我在 Unity 场景中使用的唯一模型是来自 Mixamo 的男孩模型。问题是,即使使用我的 RTX3050,动画也非常缓慢且断断续续。如果我用普通的键盘输入替换串行代码,它的动画效果会完美无缺。

以串行数据作为输入时,我需要更改什么才能使动画流畅?

c# unity-game-engine arduino
1个回答
0
投票

尝试更换线路

if (data_stream.IsOpen) {

if (data_stream.IsOpen && data_stream.BytesToRead > 0) {

另外,为了进行测试,我很想更改你的 Arduino 代码,以便每隔一两秒它就会在发送 1 和 0 之间切换,而不是每 500 毫秒随机发送一次。

© www.soinside.com 2019 - 2024. All rights reserved.