How to maintain player position between scenes?
For example, in Scene1 the player is located at (1,2,3) then the scene is changed to Scene2 and the player should be located at (1,2,3) in the new scene.
I figure I'll need to get the player position first, then change scene, and then translate the player to that position, but I don't know how I would store that position between scenes.
Answer by LiamofElites · Feb 14, 2018 at 01:11 AM
The best solution for this is to use DontDestroyOnLoad. This will keep the gameobject when transitioning to another scene.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class dontDestroy : MonoBehaviour {
int scene = 1;
void Update() {
if (Input.GetKeyDown(KeyCode.Space)) {
if (scene == 1) {
SceneManager.LoadScene("Scene1");
DontDestroyOnLoad(transform.gameObject);
scene++;
} else {
SceneManager.LoadScene("Scene");
scene--;
}
}
}
}
Thank you, this works perfectly! I had found other threads suggesting the DontDestroyOnLoad method, but I couldn't figure out how to implement it. One problem I have with this is that when I load the original scene it spawns another "player". I assume I should add some check for other player objects in a scene, do you know the best way to go about that?
I ended up using "FindGameObjectsWithTag" to find all Players, and then deleting all of them past the first. Is this a bad solution?
Sorry for the confusion, I set DontDestroyOnLoad to the same gameobject every time the scene was changed. This in turn would duplicated the gameobject from the last scene, I've updated my answer's code to
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Scene$$anonymous$$anagement;
public class dontDestroy : $$anonymous$$onoBehaviour {
int scene = 1;
void Update() {
if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Space)) {
if (scene == 1) {
DontDestroyOnLoad(transform.gameObject);
Scene$$anonymous$$anager.LoadScene("Scene1");
scene++;
} else {
Scene$$anonymous$$anager.LoadScene("Scene");
scene--;
}
}
}
}
Answer by Betoso · Feb 14, 2018 at 12:17 AM
Hello i will give you an easy solution but i don´t know if it is the best solution.
in the Start method in someone class in the player´s prefab write this lines of code.
void Start() { transform.position=new vector3(x,y,z); }
(x,y,z) are starting point. I don´t know if it is usefull for you. If you need more about it ask and i will help you if is possible.
Cheers
If the new position in the scene is changeible the way should be different. You can to get the position as you said and use don´t destroyOnLoadScene, them you translate your player to that position in the Start method. If you need more information ask.