场景加载

发布时间 2023-05-29 19:41:06作者: gatran

场景加载

1.场景的基础操作

1.1场景的创建

场景创建的快捷键Ctrl+N可以快捷创建场景,此时创建的场景为临时场景,需要保存起来后续才能使用。

1.2场景的删除

直接在文件夹中进行删除即可,因为场景中可能会有一些依赖项,因此非必要不要删除场景。

2.同步加载场景

2.1切换场景

使用的API:SceneManager.LoadScene( );

示例:

using UnityEngine;

using UnityEngine.SceneManagement;

public class Test : MonoBehaviour

{

    void Start()

    {

        SceneManager.LoadScene("Scenes/SampleScene1");

    }

}

先将两个场景导入File>Build Settings...,将含上面代码的脚本挂到待切换场景的一个物体上,该脚本可以实现将场景切换至Scenes文件夹下的SampleScene1场景播放;

地址"Scenes/SampleScene1"也可换成该场景在Build Settings...中所对应的序号。

2.2同时加载场景

使用的API:SceneManager.LoadScene( LoadSceneMode.Additive);

示例:

using UnityEngine;

using UnityEngine.SceneManagement;

public class Test : MonoBehaviour

{

    void Start()

{     

SceneManager.LoadScene("Scenes/SampleScene1",LoadSceneMode.Additive);

    }

}

先将两个场景导入File>Build Settings...,将含上面代码的脚本挂到原场景的一个物体上,该脚本可以实现将原将原场景与Scenes文件夹下的SampleScene1场景同时加载;

地址"Scenes/SampleScene1"也可换成该场景在Build Settings...中所对应的序号。

3.异步加载场景

示例

using System.Collections;

using UnityEngine;

using UnityEngine.SceneManagement;

public class Test : MonoBehaviour

{

    void Start()

    {

        StartCoroutine(Load());

    }

    private IEnumerator Load()

    {

        AsyncOperation asyncOperation=SceneManager.LoadSceneAsync("Scene/Cut");

        asyncOperation.allowSceneActivation = false;

        while (asyncOperation.progress < 0.9f)

        {

            Debug.Log("Current progress is " + asyncOperation.progress);

            yield return null;

        }

        asyncOperation.allowSceneActivation = true;

        if (asyncOperation.isDone)

        {

            Debug.Log("Finished load and skip.");

        }

        else

        {

            Debug.Log("Not finished");

        }

    }

}

不理解该段代码

4.加载场景时保留物体

使用的API:DontDestroyOnLoad( );

示例:

using UnityEngine;

using UnityEngine.SceneManagement;

public class Test : MonoBehaviour

{

    void Start()

    {

        GameObject capsule = GameObject.Find("Capsule");

        DontDestroyOnLoad(capsule);

        SceneManager.LoadScene("Scenes/SampleScene1");

    }

}

先将两个场景导入File>Build Settings...,将含上面代码的脚本挂到原场景的一个物体上,该脚本实现的功能是将原场景切换至Scenes文件夹下的SampleScene1场景后保留原场景的Cube物体及该物体下面的子物体,该代码保留的物体只能是根物体,即没有父物体的物体。

地址"Scenes/SampleScene1"也可换成该场景在Build Settings...中所对应的序号。