将游戏对象移动/转移到另一个场景 [英] Move/Transfer GameObject to another scene

查看:78
本文介绍了将游戏对象移动/转移到另一个场景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们尝试了不同的方法将 UI 对象移动到另一个场景,但都失败了.对象在 Canvas 中.

We tryed different ways to move UI-object to another scene, but we failed. Over object is in Canvas.

方法 1:我们使用了 LoadLevelAdditive,但是从第一个场景中移动了所有对象,而没有通过 Canvas 及其元素.

Method 1: we used LoadLevelAdditive, but there moved all objects from first scene without over Canvas with it's elements.

方法 2:我们使用 DontDestroyOnLoad.我们需要更改 Canvas 上的元素.DDOL 保存了场景中的最后一个位置,但我们根本无法更改对象.

Method 2: we used DontDestroyOnLoad. We need to change our element on Canvas. DDOL save last position on the scene, but we can't change object at all.

你能得到一些建议吗?

谢谢.

推荐答案

不要使用 Application.LoadLevelXXX.这些是不推荐使用的功能.如果您使用的是旧版本的Unity,请进行更新,否则您可能无法使用以下解决方案.

Don't use Application.LoadLevelXXX. These are deprecated functions. If you are using old version of Unity, please update it otherwise, you may not be able to use the solution below.

首先,使用SceneManager.LoadSceneAsync 加载场景.将 allowSceneActivation 设置为 false 以便场景在加载后不会自动激活.

First, load scene with SceneManager.LoadSceneAsync. Set allowSceneActivation to false so that the scene won't activate automatically after loading.

您的问题的主要解决方案是SceneManager.MoveGameObjectToScene 函数,用于将游戏对象从一个场景传输到另一个场景.加载场景后调用,然后调用 SceneManager.SetActiveScene 激活场景.下面是一个例子.

The main solution to your problem is the SceneManager.MoveGameObjectToScene function which is used to transfer GameObject from one scene to another. Call that after loading the scene then call SceneManager.SetActiveScene to activate the scene. Below is an example of that.

public GameObject UIRootObject;
private AsyncOperation sceneAsync;

void Start()
{
    StartCoroutine(loadScene(2));
}

IEnumerator loadScene(int index)
{
    AsyncOperation scene = SceneManager.LoadSceneAsync(index, LoadSceneMode.Additive);
    scene.allowSceneActivation = false;
    sceneAsync = scene;

    //Wait until we are done loading the scene
    while (scene.progress < 0.9f)
    {
        Debug.Log("Loading scene " + " [][] Progress: " + scene.progress);
        yield return null;
    }
    OnFinishedLoadingAllScene();
}

void enableScene(int index)
{
    //Activate the Scene
    sceneAsync.allowSceneActivation = true;


    Scene sceneToLoad = SceneManager.GetSceneByBuildIndex(index);
    if (sceneToLoad.IsValid())
    {
        Debug.Log("Scene is Valid");
        SceneManager.MoveGameObjectToScene(UIRootObject, sceneToLoad);
        SceneManager.SetActiveScene(sceneToLoad);
    }
}

void OnFinishedLoadingAllScene()
{
    Debug.Log("Done Loading Scene");
    enableScene(2);
    Debug.Log("Scene Activated!");
}

这篇关于将游戏对象移动/转移到另一个场景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆