在unity中,使用SceneManager对场景统一进行切换,但是每次切换到一个新的场景后,需要使用SceneManager.LoadScene指定下一个场景的名字,不太好统一进行场景的切换控制。
想到的一个比较简单的方法是,获取当前的场景名字,然后有规律的进行累加或者累减的方式进行,当然这种场景的名字是需要有规律的,比如说通关游戏,关数是一级一级往上累加的,然后进行LoadScene,就可以实现了一个脚本统一处理。
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Scene_Manager : MonoBehaviour
{
string[] sceneName = { "sm1", "sm2", "sm3" };
public int idx = 0;
// Start is called before the first frame update
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
string sceneName = SceneManager.GetActiveScene().name;
string currName = sceneName.Substring(sceneName.Length - 1, 1);
int nextIdx;
nextIdx = int.Parse(currName) + 1;
if (nextIdx > sceneName.Length)
{
nextIdx = 1;
}
Debug.Log("当前数字是:" + currName + ", 下一个数字是:" + nextIdx);
string nextSceneName = "sm" + nextIdx.ToString() ;
Debug.Log("当前Scene Name=" + sceneName + ", Next Scnen Name=" + nextSceneName);
SceneManager.LoadScene(nextSceneName);
}
}
}