-
使用场景
在编辑器或者发行版游戏中,如果我们想切换一个场景,需要设置触发器或者手动设置按钮来调用SceneManagement中的函数。而这个脚本挂载到场景时按下按键就可以在屏幕上方或者下方展示所有Build Setting中的场景,按下按键就可以加载对应场景
-
使用方法
将脚本挂载到任意物体上,也可以制作成预制体。在编辑器中运行游戏,按下键盘上~键(即上方数字1左边的按键)就可以调出所有场景,再按一下关闭,点击场景按钮切换到指定场景
-
可调整参数含义
-
Display Position:显示位置,可以选择顶部或者底部,默认顶部
-
Adaptive Width:开启或关闭自适应按钮宽度,默认开启
-
X Interval:调整按钮横向间距,默认3
-
Y Interval:调整按钮纵向间距,默认3
-
Button Width:调整按钮宽度,若开启自适应按钮宽度,该项不造成影响,默认100
-
Button Height:调整按钮高度,默认30
-
-
效果展示
-
代码展示
/*
* Rayhirox
* 2022-08-07
* 2022-08-08
*/
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.InputSystem;
using System.Buffers;
using Unity.VisualScripting;
using UnityEngine.InputSystem.Controls;
public class YSceneManager : MonoBehaviour
{
public enum Position { Top, Bottom };
public Position DisplayPosition = Position.Top;
public bool AdaptiveWidth = true;
public float xInterval = 3f;
public float yInterval = 3f;
public float buttonWidth = 100f;
public float buttonHeight = 30f;
private bool isDisplayed = false;
private Keyboard keyboard;
private void Update()
{
keyboard = Keyboard.current;
if (keyboard == null)
{
Debug.LogError("There is no available keyboard.");
}
if (keyboard.backquoteKey.wasPressedThisFrame)
{
isDisplayed = !isDisplayed;
}
}
private void OnGUI()
{
if (!isDisplayed) { return; }
float x = xInterval;
float y = yInterval;
if(DisplayPosition == Position.Bottom) { y = Screen.height - yInterval - buttonHeight; }
for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
{
string sceneName = SceneUtility.GetScenePathByBuildIndex(i);
var startPos = sceneName.LastIndexOf("/") + 1;
var endPos = sceneName.LastIndexOf(".");
sceneName = sceneName.Substring(startPos, endPos - startPos);
if (AdaptiveWidth)
{
buttonWidth = sceneName.Length * 6f + 20f;
}
if (sceneName != null)
{
if (x + buttonWidth + xInterval >= Screen.width)
{
if(DisplayPosition == Position.Bottom) y -= buttonHeight + yInterval;
else y += buttonHeight + yInterval;
x = xInterval;
}
if (GUI.Button(new Rect(x, y, buttonWidth, buttonHeight), sceneName))
{
AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(sceneName);
}
x += buttonWidth + xInterval;
}
}
}
}