My unity won't read a string data from Arduino to Unity

using System.Collections;
using System.Collections.Generics;
using UnityEngine;
using System.IO.Ports;
using System.Threadings;

public class sample: MonoBehavior
{
SerialPort sp = new SerialPort("COM3", 9600)
public GameObject Image;

void Start()
{
sp.close();
sp.Open();
sp.ReadTimeout = 1;
}

void Update()
{
if(sp.IsOpen)
{
try
{
ArduinoString(sp.ReadLine());
print(ArduinoString);
}
catch(System.Exception)
{
}
}

void ArduinoString(string txt)
{
if(txt == "r")
{
Image.setActive(true);
}

Arduino Code

void setup()
{
Serial.begin(9600);
Serial.write("r");
Serial.flush();
}
void loop()
{

}

Does it work from the Arduino Serial Monitor? And you’re only writing a single r character, try putting it in loop(), Unity probably misses it. Also make sure to properly debug your code Tips for new Unity users

You are calling sp.ReadLine(), which, according to the docs, reads until it reaches a newline character. Since your Arduino doesn’t send a newline, sp.ReadLine() will throw a TimeoutException after your assigned read timeout of 1ms (which might not be enough time to read something substantial anyways)

1 Like

Yeah it does work on my Serial Monitor.

And About the video you suggested when I try on Serial Monitor the “r” appeared but when it’s comes to unity it doesn’t appear on my console. print(ArduinoString);

What should I do?
Should I use Serial.println();?

What was the result when you tried our suggestions?

1 Like

Or, in your Arduino code, try

Serial.write("r\n")

You may also want to increase your sp.ReadTimeout. 10 is still quite fast.

Also, don’t discount the suggestion that your Arduino is sending the message before Unity is listening. You could try moving the Serial.write into the loop.