Scene.name
Declaration
public string name;Описание
Возвращает имя Scene, которое в данный момент активно в игре или приложении.
Scene.name возвращает строку только для чтения во время выполнения. name ограничены 244 символами. Имя Scene по умолчанию scene. Пользователь изменяет name во время создания игры.
В следующем примере скрипта Scene изменяется в зависимости от кликов GUI.Button и имени Scene. Чтобы этот пример работал:
- Создайте Project с двумя сценами,
scene1иscene2. - Прикрепите скрипт ниже к GameObject, добавленному к
scene1. - Прикрепить тот же скрипт к GameObject, добавленным к
scene2. - Нажмите на GameObject и перейдите к Inspector.
- В поле
My First Sceneи полеMy Second Sceneвведите имена сцен, между которыми вы хотите переключаться,scene1иscene2. - Выберите
scene1, дважды щелкнув по нему в Project, и нажмитеPlay. Появится сценаscene1. - Нажмите кнопку
Load Next Sceneиscene2будет загружено.
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;
public class Example : MonoBehaviour { // These are the Scene names. Make sure to set them in the Inspector window. public string myFirstScene, mySecondScene;
private string nextButton = "Load Next Scene"; private string nextScene; private static bool created = false;
private Rect buttonRect; private int width, height;
void Awake() { Debug.Log("Awake:" + SceneManager.GetActiveScene().name);
// Ensure the script is not deleted while loading. if (!created) { DontDestroyOnLoad(this.gameObject); created = true; } else { Destroy(this.gameObject); }
// Specify the items for each scene. Camera.main.clearFlags = CameraClearFlags.SolidColor; width = Screen.width; height = Screen.height; buttonRect = new Rect(width / 8, height / 3, 3 * width / 4, height / 3); }
void OnGUI() { // Return the current Active Scene in order to get the current Scene name. Scene scene = SceneManager.GetActiveScene();
// Check if the name of the current Active Scene is your first Scene. if (scene.name == myFirstScene) { nextButton = "Load Next Scene"; nextScene = mySecondScene; } else { nextButton = "Load Previous Scene"; nextScene = myFirstScene; }
// Display the button used to swap scenes. GUIStyle buttonStyle = new GUIStyle(GUI.skin.GetStyle("button")); buttonStyle.alignment = TextAnchor.MiddleCenter; buttonStyle.fontSize = 12 * (width / 200);
if (GUI.Button(buttonRect, nextButton, buttonStyle)) { SceneManager.LoadScene(nextScene); } } }
В следующем примере используются две сцены, и одна из них имеет длинное Scene имя с 244 цифрами. Другая называется testScene. Чтобы сделать этот пример работающим:
1. Создайте новую Project.
2. Измените имя сцены по умолчанию на testScene, выбрав ее и затем используя Assets->Rename.
3. Затем создайте вторую сцену и снова выберите ее и используйте Asset->Rename. Используйте имя, как показано ниже. (Это 244 символьное имя "0123456789...0123").
4. Создайте C# Скрипт и назовите его Example.cs.
5. Добавьте следующий текст скрипта в Example.cs.
6. Затем добавьте пустую GameObject, названную GameObject в каждую из двух сцен.
7. Наконец, скопируйте Example.cs в каждую из двух GameObjects.
Используйте кнопку Game для запуска сцены testScene. Отображается кнопка GUI, которая позволяет сменить сцены.
using UnityEngine; using UnityEngine.SceneManagement;
// SceneManagement.SceneManager-name example
public class Example : MonoBehaviour { private Scene scene;
void Start() { scene = SceneManager.GetActiveScene(); Debug.Log("Name: " + scene.name); }
void OnGUI() { if (GUI.Button(new Rect(10, 10, 150, 100), "Change Scene")) { if (scene.name == "testScene") { // The scene to load has a 244 characters name. SceneManager.LoadScene("0123456789012345678901234567890123456789" + "012345678901234567890123456789012345678901234567890123456789" + "012345678901234567890123456789012345678901234567890123456789" + "012345678901234567890123456789012345678901234567890123456789" + "012345678901234567890123"); } else { SceneManager.LoadScene("testScene"); } } } }