はじめに
この記事は、Unityで複数のsceneを切り替える手順を説明したものです。
環境
Unity 2019.4.17f1
ポイント
sceneを追加するには、Hierarchyじゃなくて、ProjectタブのAssetsの中に追加する。それだけでは足りなくて、Build SettingのScene In Buildingに作ったSceneをD&Dで追加する必要がある。編集対象を切り替えるには、Assetsの各sceneをダブルクリックで、選択すればよい。
シーン変更コマンドは、
SceneManager.LoadScene("xxxxx");
ただし、冒頭にこれを書く必要がある。
using UnityEngine.SceneManagement;
手順
1、Assetsにあるデフォルトのシーンファイルをscene1に名前変更する。
2、新規にscene2を作成する
3、スクリプトtoScene2と、toScene1を作成し、内容を下記に変更。
4、scene1に適当なボックスを作成し、toScene2.csをアタッチ。
5、scene2に適当な球を作成し、toScene1.scをアタッチ。
6、Build SettingのScene In Buildingにscene2も放り込み、2つのシーンがある状態にする。
7、実行して、スペースキーで、切り替わりを確認する。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;//追加
public class toScene2 : MonoBehaviour{
void Start(){
}
void Update(){
if (Input.GetKey(KeyCode.Space)) {
SceneManager.LoadScene("scene2");
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;//追加
public class toScene1 : MonoBehaviour{
void Start(){
}
void Update(){
if (Input.GetKey(KeyCode.Space)) {
SceneManager.LoadScene("scene1");
}
}
}