场景切换前提:
首先要想切换场景,场景必须已经在build窗口中存在。
然后才能根据代码来跳转切换场景。
跳转切换场景的代码有两种一种是旧版的方法 Application.LoadLevel("SampleScene");另一种是新版的方法 SceneManager.LoadScene("SampleScene");
具体看案例:
新建场景,方法如下:File ---New scene就可以新建场景。如图:
之后按 Ctrl+S 保存场景。
-----本案例,有三个场景,SampleScene,1,2。如图:
为了区分三个场景内的东西,我在SampleScene里放置了一个plane
场景1中放置了物体 cube
场景2中放置了物体sphere
接下来要对三个场景进行切换。
-------
刚说过,要想跳转场景必须将场景放入build setting里的上面。
放入之后会看到每个场景右边都有一个编号,这个就是顺序,可以理解为数组。从下标0开始。如图:
打开场景1新建脚本changescene,挂到cube上。
运行,点击鼠标右键便可切换场景。
代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Changescene : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//点击鼠标右键切换场景
if (Input.GetMouseButtonDown(1))
{
Application.LoadLevel(2);
}
}
}
Unity中切换场景使用的是Application.LoadLevel()函数,括号中加入场景的名称或编号即可,
上述脚本括号中的2指的是场景序号下标,如下图
如果括号中要写成场景名称也可以,下标为2的场景对应的名字是:SampleScene。所以可以写成如下方式:
------至此方法一over,接下来是第二种跳转方法----
只有代码上的修改,其他设置一律同第一种方法。代码如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Changescene : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//点击鼠标右键切换场景
if (Input.GetMouseButtonDown(1))
{
// Application.LoadLevel("SampleScene");
SceneManager.LoadScene("SampleScene");
}
}
}
要使用第二种方法,必须using UnityEngine.SceneManagement;这是新版unity里的切换场景的方法。