How to Teleport Between Scenes in Unity

Teleporting between scenes in Unity is a useful feature for transitioning players between different levels or areas. This tutorial covers how to implement scene teleportation using additive scene loading, ensuring player data persistence, and unloading the old scene after the teleportation. This approach ensures a smooth transition without losing player data or objects.

Setting Up Scenes and Teleportation Points

First, we'll set up the scenes and designate teleportation points within them.

Creating Scenes

  1. In Unity, go to File > New Scene to create a new scene. Save it in your Assets folder, naming it Scene1.
  2. Repeat the process to create another scene named Scene2.
  3. Add both scenes to the build settings by going to File > Build Settings and clicking Add Open Scenes.

Designating Teleportation Points

Each scene needs a designated point where the player will appear after teleportation.

  1. In Scene1, create an empty GameObject and name it TeleportPoint1. Tag it appropriately, for example, as SpawnPoint.
  2. In Scene2, create another empty GameObject named TeleportPoint2 and tag it similarly.
  3. These GameObjects will serve as spawn locations when transitioning between scenes.

Creating a Teleportation Script

The teleportation script manages the scene transition, ensuring the player moves to the correct location in the new scene, and then unloads the previous scene.

Teleportation Script

using UnityEngine;
using UnityEngine.SceneManagement;

public class Teleportation : MonoBehaviour
{
    public string sceneToLoad; // Name of the scene to load
    public string spawnPointTag = "SpawnPoint"; // Tag for identifying the spawn point

    private string currentSceneName; // To track the current scene

    void Start()
    {
        currentSceneName = SceneManager.GetActiveScene().name;
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            DontDestroyOnLoad(other.gameObject); // Prevent player object from being destroyed

            SceneManager.LoadScene(sceneToLoad, LoadSceneMode.Additive); // Load new scene additively
            SceneManager.sceneLoaded += OnSceneLoaded; // Register callback for scene load completion
        }
    }

    void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        if (scene.name == sceneToLoad)
        {
            // Find the spawn point in the newly loaded scene
            GameObject spawnPoint = GameObject.FindWithTag(spawnPointTag);
            if (spawnPoint != null)
            {
                GameObject player = GameObject.FindWithTag("Player");
                if (player != null)
                {
                    // Teleport the player to the spawn point
                    player.transform.position = spawnPoint.transform.position;
                }
            }

            // Unload the previous scene
            SceneManager.UnloadSceneAsync(currentSceneName);

            // Update the current scene name and unregister the event handler
            currentSceneName = sceneToLoad;
            SceneManager.sceneLoaded -= OnSceneLoaded;
        }
    }
}
  1. Create a new C# script named Teleportation.cs in the Scripts folder.
  2. Attach this script to an object that will act as a teleport trigger, such as a door or portal.
  3. Set the sceneToLoad to the name of the scene to transition to, and ensure the teleportation point in the new scene is tagged correctly.

Handling Player Data Across Scenes

If your game requires maintaining player data (like inventory, health, etc.) across scenes, implement a data persistence strategy.

Persistent Player Data

using UnityEngine;

public class PlayerData : MonoBehaviour
{
    public static PlayerData instance;

    public int health = 100;

    void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }
}
  1. Create a new C# script named PlayerData.cs and attach it to the player object or a separate GameObject.
  2. Ensure this GameObject is not destroyed during scene transitions by using DontDestroyOnLoad(gameObject).

Conclusion

Teleporting between scenes in Unity, especially with additive scene loading and unloading, provides a seamless experience. This method retains important game objects like the player and manages resources efficiently by unloading the previous scene. Such an approach is particularly useful in games with large or continuous environments. Customize this setup further to suit specific gameplay requirements, like maintaining state data or adding visual effects during transitions.