Hi! I am a newbie trying to learn creating a game for my fyp. So my game about a maze game (using a fpc) and inside the maze, there consist several checkpoint that triggers when player collide with the checkpoint. The problem right now is that after the player finished inside the checkpoint’s scene (2D game) and go back to the main game scene, they always respawn at the exact first place of the starting game. I am trying to make them respawn back near the checkpoint that they have finished. I tried using
the save and load player position data but it doesn’t work. Please help me. Thank you.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SavePlayerPos : MonoBehaviour
{
public GameObject player;
private void Start()
{
if(PlayerPrefs.GetInt("Saved") == 1 && PlayerPrefs.GetInt("TimeToLoad") == 1)
{
float pX = player.transform.position.x;
float pY = player.transform.position.y;
float pZ = player.transform.position.z;
pX = PlayerPrefs.GetFloat("p_x");
pY = PlayerPrefs.GetFloat("p_y");
pZ = PlayerPrefs.GetFloat("p_z");
player.transform.position = new Vector3(pX, pY, pZ);
PlayerPrefs.SetInt("TimeToLoad", 0);
PlayerPrefs.Save();
}
}
public void PlayerPosSave()
{
PlayerPrefs.SetFloat("p_x", player.transform.position.x);
PlayerPrefs.SetFloat("p_y", player.transform.position.y);
PlayerPrefs.SetFloat("p_z", player.transform.position.z);
PlayerPrefs.SetInt("Saved", 1);
PlayerPrefs.Save();
}
public void PlayerPosLoad()
{
PlayerPrefs.SetInt("TimeToLoad", 1);
PlayerPrefs.Save();
}
}
and this is my script for the object that triggers the changing scene
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ChangeScene : MonoBehaviour
{
SavePlayerPos playerPosData;
void Start()
{
playerPosData = FindObjectOfType<SavePlayerPos>();
}
public void GoBackToGame1()
{
playerPosData.PlayerPosSave();
playerPosData.PlayerPosLoad();
SceneManager.LoadScene("Level 1");
}