文章目录
效果
在scene1中点击按钮,进入scene2。
实现步骤
1.创建场景
在Assets中右键创建两个场景,Scene1和Scene2(我的是MainScene)。
2.添加按钮
双击新建的Scene1,在Hierachy中添加Button;这个Button会出现一个Canvas下面,场景中也会出现一个Button。
3. 写C#脚本实现切换
在Asset中右键创建C# Script,命名为Start_Scene。
代码如下,主要是应用UnityEngine.UI和UnityEngine.SceneManagement,然后记得保存。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Start_Scene : MonoBehaviour
{
// Start is called before the first frame update
void Start() {
// Obtain the Button in Scene 1.
Button btn = transform.GetComponent<Button>();
// Banding a function for Button Click.
btn.onClick.AddListener(eventListener);
}
// Update is called once per frame
void Update() {}
// Button Click - Switch to Another Scene.
void eventListener() {
SceneManager.LoadScene("MainScene");
}
}
4. 添加Component到Button上
在Hierarchy中选中Button,再把Assets的脚本拖到Add Component上,就会出现右侧框的内容。
5. 添加两个Scene到Build中
打开Build Setting窗口(File->Build Setting),在Assets中同时选中两个Scene,拖进Scenes in Build中。
测试效果
点这个Play,再点图中的Button。
注意:记得先进入Scene1再点Play。
参考资料
Unity3D 场景切换