- 需要将 Unity API改成 .Net Framework 其他的不支持
| using System; |
| using System.IO.Ports; |
| using System.Text; |
| using System.Threading; |
| using UnityEngine; |
| |
| public class MainController : MonoBehaviour |
| { |
| public string portName; |
| public int baudRate; |
| public Parity parity; |
| public int dataBits; |
| public StopBits stopBits; |
| |
| private SerialPort _serialPort; |
| private Thread _thread; |
| private void Start() |
| { |
| _serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits); |
| _serialPort.Open(); |
| _thread = new Thread(new ThreadStart(DataReceived)); |
| _thread.Start(); |
| } |
| |
| private void DataReceived() |
| { |
| while (true) |
| { |
| if (_serialPort.IsOpen) |
| { |
| int count = _serialPort.BytesToRead; |
| if (count > 0) |
| { |
| byte[] readBuffer = new byte[count]; |
| try |
| { |
| _serialPort.Read(readBuffer, 0, count); |
| print(Encoding.UTF8.GetString(readBuffer)); |
| |
| } |
| catch (Exception ex) |
| { |
| Debug.Log(ex.Message); |
| } |
| } |
| } |
| Thread.Sleep(10); |
| } |
| } |
| |
| public void DataProcessing(byte[] data) |
| { |
| StringBuilder sb = new StringBuilder(); |
| for (int i = 0; i < data.Length; i++) |
| { |
| sb.AppendFormat("{0:x2}" + "", data[i]); |
| } |
| Debug.Log(sb.ToString()); |
| } |
| private void Update() |
| { |
| if (Input.GetKeyDown(KeyCode.Space)) |
| { |
| byte[] buffer = Encoding.UTF8.GetBytes("你好啊"); |
| _serialPort.Write( buffer, 0, buffer.Length); |
| } |
| |
| |
| } |
| |
| private void OnDestroy() |
| { |
| if (_serialPort != null && _serialPort.IsOpen) |
| { |
| _serialPort.Close(); |
| print("已经关闭"); |
| } |
| if (_thread != null && _thread.IsAlive) |
| { |
| print("线程关闭"); |
| _thread.Abort(); |
| } |
| } |
| } |