整体代码:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO.Ports;
using UnityEngine;
using UnityEngine.UI;
public class Mabagenment : MonoBehaviour
{
//可用串口号缓存
private string[] serial_A;
//串口号缓存
private string serial_Name;
//波特率
private int baudRate = 9600;
//开关串口判断
private bool close = false;
//串口号文本
public Text portNames_text;
//连接状态显示
public GameObject close_gameobject;
//实例化一个串口
public SerialPort serialPort = new SerialPort();
//开关串口
public Text CLose;
//开关串口提示
public Text Nhint_Text;
public Dropdown dropdiwb;
private void Start()
{
//获取串口号
serial_A = SerialPort.GetPortNames();
//赋值串口号
serial_Name = serial_A[0];
//显示串口号
portNames_text.text = serial_Name;
}
//搜索设备
public void GetSerialPort_Names()
{
//重置数组
for (int i = 0; i < serial_A.Length; i++)
{
serial_A[i] = "";
}
//赋值串口号
for (int i = 0; i < serial_A.Length; i++)
{
serial_A = SerialPort.GetPortNames();
List<string> inside = new List<string> { serial_A[i] };
dropdiwb.AddOptions(inside);
}
//获取串口号
serial_A = SerialPort.GetPortNames();
//显示串口号
portNames_text.text = serial_Name;
}
private void Open_SerialPort()
{
if (!close)
{
try
{
//定义串口属性变量
serialPort = new SerialPort(serial_Name, baudRate);
//开启串口
serialPort.Open();
close_gameobject.SetActive(true);
CLose.text = "关闭串口";
Nhint_Text.text = "串口已打开";
close = true;
}
//报错处理
catch (Exception EX)
{
//关闭串口
serialPort.Close();
close_gameobject.SetActive(false);
throw;
}
}
else
{
//关闭串口
serialPort.Close();
close = false;
CLose.text = "打开串口";
close_gameobject.SetActive(false);
}
}
//返回菜单
public void Show()
{
gameObject.SetActive(true);
}
public void Hit()
{
gameObject.SetActive(false);
}
//退出
public void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
编辑器状态下:
打开串口:
关闭串口:
参数面板: