using UnityEngine; using UnityEngine.SceneManagement; using System.IO.Ports; public class HardwareSceneSwitch : MonoBehaviour { [Header("填写你的Arduino COM口号")] public string comPort = "COM3"; public int baudRate = 9600; private SerialPort serial; void Start() { // 打开串口 serial = new SerialPort(comPort, baudRate); serial.ReadTimeout = 10; try { serial.Open(); Debug.Log("串口已连接,按下硬件按键切换下一场景"); } catch { Debug.LogError("串口打开失败,检查COM口、关闭Arduino串口监视器"); } } void Update() { if (!serial.IsOpen || serial.BytesToRead <= 0) return; string rec = serial.ReadLine().Trim(); // 收到Arduino的切换指令 if (rec == "NEXT") { serial.Close(); LoadNextScene(); } } // 加载下一个场景,末尾循环回第一个场景 void LoadNextScene() { int currentIndex = SceneManager.GetActiveScene().buildIndex; int totalScenes = SceneManager.sceneCountInBuildSettings; int nextIndex = currentIndex + 1; // 到达最后一个场景,切回第一个场景 if (nextIndex >= totalScenes) nextIndex = 0; SceneManager.LoadScene(nextIndex); } // 切换场景/退出时关闭串口,防止占用 void OnDestroy() { if (serial != null && serial.IsOpen) serial.Close(); } }