How To Save Serial Port Data to a Variable?

Hello, I am streaming Input Data from a hardware device with sensors through the Serial Port and into Unity. Here is my code streaming into Unity. I need to save the data that is being printed to the Console Log to a variable that I can use. Any ideas?

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

public class CountTest : MonoBehaviour {
SerialPort sp = new SerialPort("COM9", 57600);
	
	void Start () {
		sp.Open ();
		sp.ReadTimeout = 1;
	}
	void Update () 
	{
		try{
		       print (sp.ReadLine());
		}
		       catch(System.Exception){
		}

string line = sp.ReadLine();

…that’s about it. I’m not sure I see what the problem is.

However, you should know that .ReadLine() blocks the thread until a message is received. Since you put that line in the Update() loop, the main Unity thread will be blocked by this script, and either block the game entirely or cause severe frame rate drops, even when your device is sending messages regularly. Because the DataReceived event does not work in Unity’s Mono version, you will need to read the serial port input on a separate thread and feed it back to the main thread in a safe way.

Here is the code to do so:

public class SerialComms
{
    private const string PORT = "COM3";
    private SerialPort _port;
 
    public int LatestLine{ get; set; }
 
    private bool _runThread = true;
 
    public SerialComms()
    {
        _port = new SerialPort(PORT, 9600);
        _port.Open();
 
        Thread pollingThread = new Thread(RunPollingThread) { IsBackground = true };
        pollingThread.Start();
    }
 
    public void Stop()
    {
        _runThread = false;
        _port.Close();
    }
 
    private void RunPollingThread()
    {
        while (_runThread)
        {
            PollArduino();
        }
    }
 
    private void PollArduino()
    {
        if (!_port.IsOpen)
            return;
 
       LatestLine = _port.ReadLine();
    }
}

In your MonoBehaviour, you will have to create an instance of this SerialComms class, and check the LatestLine property in the Update() loop. Also, be sure to Stop() it in OnApplicationQuit().

@ThomasMountainborn : Thank you for the reply, The first line about string line = sp.ReadLine(); is what I was trying to achieve only I need an integer. Sorry I wasn’t clear in my original statement but I basically am looking for this:

int A = sp.ReadLine();
int B = 5;

A * B = x;

Debug.Log(x);