Im connecting my arduino to Unity using System.IO.Ports. However, I have been now dealing with trying to convert the string from the ReadLine() method to an integer, as that is all that is being sent from the arduino (its a distance sensor, giving the distance in cm). I tried the int.Parse method but for some reason that never worked either.
Any help would be greatly appreciated.
Here’s my C# code:
using UnityEngine;
using System.Collections;
using System.IO.Ports;
public class ArduinoConnect : MonoBehaviour {
SerialPort str= new SerialPort("COM3", 9600);
public GameObject forceObject;
//public static int Dist;
// Use this for initialization
void Start () {
str.Open();
str.ReadTimeout = 1;
}
// Update is called once per frame
void Update () {
if (str.IsOpen) {
try {
//---------START OF TRY---------------------------------------
Debug.Log("Distance: "+ str.ReadLine());
if (int.Parse(str.ReadLine()) () < 20) {
forceObject.rigidbody.constantForce.force=Vector3.up*10000;
}
else {
forceObject.rigidbody.constantForce.force=Vector3.zero;
}
//---------------------END OF TRY--------------------------------------------------
}
catch (System.Exception) {
}
}
}
}