Building on the answer by @RomanLed. You can use this script to move an object from one scene to another:
using UnityEngine;
using UnityEngine.SceneManagement;
static public class MoveObjectToNewScene
{
static GameObject targetObject;
static string targetSceneName;
static Scene currentScene;
static Scene newScene;
/// <summary>
/// Move a GameObject from the current scene to another scene.
/// </summary>
/// <param name="sceneName">Name of the scene you want to load.</param>
/// <param name="targetGameObject">GameObject you want to move to the new scene.</param>
static public void LoadScene(string sceneName, GameObject targetGameObject)
{
// set some globals
targetObject = targetGameObject;
targetSceneName = sceneName;
// get the current active scene
currentScene = SceneManager.GetActiveScene();
// load the new scene in the background
SceneManager.LoadSceneAsync(targetSceneName, LoadSceneMode.Additive);
// Attach the SceneLoaded method to the sceneLoaded delegate.
// SceneLoaded will be called when the new scene is loaded.
SceneManager.sceneLoaded += SceneLoaded;
}
/// <summary>
/// After new scene loads, move GameObject from current scene to new scene.
/// When finished, unload current scene. The new scene becomes current scene.
/// </summary>
/// <param name="newScene">New scene that was loaded.</param>
/// <param name="loadMode">Mode that was used to load the scene.</param>
static public void SceneLoaded(Scene newScene, LoadSceneMode loadMode)
{
// remove this method from the sceneLoaded delegate
SceneManager.sceneLoaded -= SceneLoaded;
// get the scene we just loaded into the background
newScene = SceneManager.GetSceneByName(targetSceneName);
// move the gameobject from scene A to scene B
SceneManager.MoveGameObjectToScene(targetObject.gameObject, newScene);
// unload scene A
SceneManager.UnloadSceneAsync(currentScene);
}
}
Here is how you could use this script:
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour {
void Start () {
MoveObjectToNewScene.LoadScene("sceneA", this.gameObject);
}
}
@The Vaffel This script, when attached to any gameObject, will load a scene and move the gameObject to that scene. When calling the “ChangeScene” method, send it the scene index of the next scene.
void ChangeScene(int nextSceneIndex) //index of scene to move to
{
SceneManager.LoadScene(nextSceneIndex, LoadSceneMode.Additive);
Scene nextScene = SceneManager.GetSceneAt(SceneManager.sceneCount - 1);
SceneManager.MoveGameObjectToScene(gameObject, nextScene);
}
the above method will load another scene additively and keep the first, while moving the object. the coroutine below will delete the previous scene. make sure to yield null.
@The Vaffel I’ve been looking around trying to find solutions to avoid using DontDestroyOnLoad (since it’s highly recommended not to use it in the documentation), but I’m having the same problem with moving objects from one scene to another. Have you found a solution ?