I am creating a simple unity program where a serial data is sent from Arduino and processed in Unity using C#. Depending on the value received, two different animations are played.
Arduino Code:
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# code:
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 sends the data and Unity receives it perfectly fine. The only model I use in the Unity scene is the boy model from Mixamo. The problem is that the animation is really slow and choppy even with my RTX3050. If I replace the serial code with an ordinary keyboard input, it animates flawlessly.
What do I need to change to make the animations smooth while taking serial data as input?
Try replacing your line
if (data_stream.IsOpen) {
with
if (data_stream.IsOpen && data_stream.BytesToRead > 0) {
Also for the sake of testing I would be tempted to change your Arduino code so that every second or two it flipped between sending a 1 and a zero, rather than randomly every 500ms.