2022-03-09 switching between two scenes of unity 3D

Time:2022-5-3

effect

Click the button in Scene1 to enter scene2.

Implementation steps

1. Create a scene

Right click in assets to create two scenes, Scene1 and scene2 (my main scene).
2022-03-09 switching between two scenes of unity 3D

2. Add button

Double click the new Scene1 and add a button in hierachy; This button will appear under canvas, and a button will also appear in the scene.
2022-03-09 switching between two scenes of unity 3D

3. Write c# script to realize switching

Right click in asset to create a c# script named start_ Scene。
2022-03-09 switching between two scenes of unity 3D
The code is as follows, mainly referring to unityengine UI and unityengine SceneManagement; Remember to modify the name of the loaded second scene in EventListener. If scene2 is created earlier, change it and save it.

Note: Here I only use one parameter for loadscene, which means that Scene1 will be destroyed. If Scene1 will be returned from scene2 later, to add other parameters, please see:Unity3d switches to loading scene SceneManager LoadScene

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. Add component to button

Select button in hierarchy, and then drag the script of assets to add component, and the contents in the box on the right will appear.
2022-03-09 switching between two scenes of unity 3D

5. Add two scenes to build

Open the build setting window (file – > build setting), select two scenes in assets at the same time, and drag them into scenes in build.
2022-03-09 switching between two scenes of unity 3D

Test effect

Click play, and then click the button in the figure.
Note: remember to enter Scene1 first and then click play.
2022-03-09 switching between two scenes of unity 3D

reference material

Unity3d scene switching
Unity3d switches to loading scene SceneManager LoadScene

Recommended Today

Generate QR code in Python

This paper introduces the basic use of a QR code library that can be associated. Myqr (amzqr) is very convenient to use Myqr (amzqr) library You can generate ordinary QR code, art QR code (black and white or color), and animation QR code (black and white or color). At present, the official website seems to […]