Hey Guys,
I’m making a game in which the player moves around in a scene, and at certain points, the scene changes, and when it returns to the original scene, the player needs to be placed at the position in which they were at when the scene changed. The way I’m attempting to do it is to cache the player position in a vector3 that is in a script on a persistent game object that isn’t destroyed between scenes. When the game returns to the first scene, the player position is set to be equal to the vector3 that is holding its last position. But for the life of me, I cannot get it to work. The player always ends up at the origin every time.
Here is my code. Please let me know what I’ve done incorrectly.
A “static manager” script
public class Sm : MonoBehaviour
{
public static Player player;
public static GM gm;
}
A DontDestroyOnLoad script to keep the game manager object persistent
public class DontDestroyOnLoad : MonoBehaviour
{
public static DontDestroyOnLoad Instance { get; private set; }
void Awake()
{
if(Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
}
}
The player script
public class Player : MonoBehaviour
{
public Transform playerTransform;
private void Awake()
{
Sm.player = this;
}
private void Start()
{
playerTransform.position = Sm.gm.playerPos;
}
}
The persistent game object
public class GM : MonoBehaviour
{
// this is the persistent game object script
public Vector3 playerPos;
private void Awake()
{
Sm.gm = this;
}
public void SavePlayerPosition()
{
playerPos = Sm.player.playerTransform.position;
}
}
The script used to move between scenes
public class ButtonManager : MonoBehaviour
{
public void Scene1()
{
SceneManager.LoadScene("Scene1");
}
public void Scene2()
{
Sm.gm.SavePlayerPosition();
SceneManager.LoadScene("Scene2");
}
}
No, actually, I've got that on a different script on the same game object. The game object persists between the scenes fine. I just can't successfully update the player's position upon returning to scene 1.
– MerlinsMaster