0

so i created life system, whenever player dies it substracts one life and when there is no more life left it takes player to game over screen, however when player goes from one scene to another life counter resets, is there any easy way to fix this? im new to programming so its hard for me to understand complexed solutions. Here is the code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameControlScript : MonoBehaviour
{

    public GameObject heart1, heart2, heart3, heart4;
    public static int health;
  
    void Start()
    {
        health = 4;
        heart1.gameObject.SetActive (true);
        heart2.gameObject.SetActive(true);
        heart3.gameObject.SetActive(true);
        heart4.gameObject.SetActive(true);
        
    }


    void Update()
    {
        if (health > 4)
            health = 4;

        switch (health) {
            case 4:
                heart1.gameObject.SetActive(true);
                heart2.gameObject.SetActive(true);
                heart3.gameObject.SetActive(true);
                heart4.gameObject.SetActive(true);
              break;

            case 3:
                heart1.gameObject.SetActive(true);
                heart2.gameObject.SetActive(true);
                heart3.gameObject.SetActive(true);
                heart4.gameObject.SetActive(false);
              break;

            case 2:
                heart1.gameObject.SetActive(true);
                heart2.gameObject.SetActive(true);
                heart3.gameObject.SetActive(false);
                heart4.gameObject.SetActive(false);
              break;

            case 1:
                heart1.gameObject.SetActive(true);
                heart2.gameObject.SetActive(false);
                heart3.gameObject.SetActive(false);
                heart4.gameObject.SetActive(false);
              break;

            case 0:
                heart1.gameObject.SetActive(false);
                heart2.gameObject.SetActive(false);
                heart3.gameObject.SetActive(false);
                heart4.gameObject.SetActive(false);
                SceneManager.LoadScene(3); 
              break;

        }
    }
}
DiplomacyNotWar
  • 31,605
  • 6
  • 57
  • 75
  • 2
    Store the value using [PlayerPrefs](https://docs.unity3d.com/ScriptReference/PlayerPrefs.html) and then retrieve it when needed in whichever scene. Everytime you update `health` variable, save it using `PlayerPrefs.SetInt ( "Health", currentHealth )` and now in a different scene just use `PlayerPrefs.GetInt ( "Health", defaultValue )` – nIcE cOw Nov 30 '21 at 01:57

0 Answers0