
How to move Player between scenes with Unity3D
Hello everyone,
Thank you for coming over to my site. I really appreciate it. In this guide I want to show you how you can load multiple scenes and spawn your main player in and out of the scenes. I have some issue with moving my character between scenes, so I wanted to share my solution.
This guide will help with the following issues:
- Loading player into scenes
- How to load character between scenes
- loading scenes with player location.
Scripts below ( use video for explanation)
Startup Script:
using System.Collections; using UnityEngine.SceneManagement; using UnityEngine; public class Startup : MonoBehaviour { void Start() { StartCoroutine(startingGame()); } IEnumerator startingGame() { yield return new WaitForSeconds(4); SceneManager.LoadScene("Lvl1"); } }
Leaving scene script:
using UnityEngine.SceneManagement; using UnityEngine; public class LeaveScene : MonoBehaviour { public string ScToLoad; private void OnTriggerEnter(Collider other) { if (other.CompareTag("Player")) { Destroy(other.gameObject); SceneManager.LoadScene(ScToLoad); } } }
Spanpoint prefab script:
using UnityEngine.SceneManagement; using UnityEngine; public class spawnpoint : MonoBehaviour { private Transform SpawnOutLocation; public string ScToLoad; // Start is called before the first frame update void Start() { SpawnOutLocation = this.gameObject.transform.GetChild(0); } private void OnTriggerEnter(Collider other) { if (other.CompareTag("Player")) { //code here the location of where to come back to SpawnOutLocation Destroy(other.gameObject); SpawnManager.SharedInstance.SetSpawn(SpawnOutLocation.position); SceneManager.LoadScene(ScToLoad); } } }
Singleton SpawnManager:
using UnityEngine; public class SpawnManager : MonoBehaviour { public static SpawnManager SharedInstance { get; private set; } public GameObject DefaultPlayer; private Transform defaultPoint; private Vector3 spawnlocation; private bool SetPoint; public void SetSpawn(Vector3 x) { SetPoint = true; spawnlocation = x; } private void Awake() { if (SharedInstance == null) { SharedInstance = this; DontDestroyOnLoad(gameObject); } else Destroy(gameObject); } private void OnLevelWasLoaded(int level) { print(spawnlocation); if(level > 1) { Transform temp = GameObject.Find("SpawnHere").transform; Instantiate(DefaultPlayer, temp.position, Quaternion.identity); } if(level == 1) { if (!SetPoint) { Debug.Log("No set location - Will Spawn at Defualt"); spawnAtStart(); } else { spawnAtSetlocation(); } } } void spawnAtSetlocation() { Debug.Log("Done spwaning at set location"); Instantiate(DefaultPlayer, spawnlocation, Quaternion.identity); SetPoint = false; } void spawnAtStart() { defaultPoint = GameObject.Find("DefaultPoint").transform; Instantiate(DefaultPlayer, defaultPoint.position, defaultPoint.rotation); } }