I made a 2D game in unity.
And I set a trap when the player has a collision on it, it will dead and can’t move.
Meanwhile,I load the same scene to make my character reborn and reset the objects.
I set the key “Tab” to use SceneManager.loadscene.
But I don’t know where to set the text about number of lives.
I use PlayerPrefs to set and get int,but it seems that the number will be reseted when the scene reload.
When I start the game and make the player die,while I press Tab,it becomes 2 but turn back to 3 in a second.
Is it because the scene reload?
Script 1:
public class MainMenu : MonoBehaviour
{
public int currentlive;
public void NewGame()
{
PlayerPrefs.SetInt("currentLives", currentlive);
}
}
Script 2:
void Start()
{
life = PlayerPrefs.GetInt("currentLives");
}
void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag=="Trap")
{
object1.SetActive(true); //Show Trap
run = false;
jump = false;
dead = true; //animations
lifecounter--; //lives decrease
PlayerPrefs.SetInt("currentLives", lifecounter);
}
}
Script 3:
void Update();
{
if (dead == true) //start the dead animation
{
player.GetComponent<Player>().enabled = false; //To make the player can't move
if (Input.GetKeyDown(KeyCode.Tab))
{
EditorSceneManager.LoadScene(EditorSceneManager.GetActiveScene().name); //reload scene
Life.text = "X " + PlayerPrefs.GetInt("currentlife"); //show the lives on the game
}
}
}