Hi,
I wanted to experiment with a code that I have learnt from online (click here for video). On it’s own, it works well. However, I want to add an element where if you take damage, it will reset the level AND keep data of how many lives have been lost. (Currently, the script will reset your life count when the level is reset)
Damage Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Damage : MonoBehaviour
{
public GameObject deathEffect, playerHealth;
void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player") //This ensures that you only lose health when the enemy hits the player.
{
GameControl3L.health -= 1; //Loads the separate script (which works well) and will remove 1 life when you collide with the enemy.
SceneManager.LoadScene("SetUp");
DontDestroyOnLoad(playerHealth);
//Add new mechanic here to restart the level and keep all health remaining.
}
}
}
FYI - Here is the other code that I have used along with this:
Game Control Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameControl3L : MonoBehaviour
{
public GameObject heart1, heart2, heart3, heart4, gameOver;
void Start()
{
health = 4;
heart1.gameObject.SetActive (true);
heart2.gameObject.SetActive (true);
heart3.gameObject.SetActive (true);
heart4.gameObject.SetActive (true);
gameOver.SetActive (false);
}
void Update()
{
if (health > 4)
{
health = 4;
}
switch (health)
{
case 4: //When no damage is taken, lose no health.
heart1.gameObject.SetActive (true);
heart2.gameObject.SetActive (true);
heart3.gameObject.SetActive (true);
heart4.gameObject.SetActive (true);
break;
case 3: //for every health lost, remove 1 heart.
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;
default: //also shown if 0 hearts are showing (case 0).
heart1.gameObject.SetActive (false);
heart2.gameObject.SetActive (false);
heart3.gameObject.SetActive (false);
heart4.gameObject.SetActive (false);
gameOver.gameObject.SetActive (true);
SceneManager.LoadScene("Skills - GameOver");
break;
} //Adjustments - *Keep current live count after restart.
//*E.g. You lost 1 life, after restart, you have 3 lives (NOT 4 lives).
}
}
I have tired using the ‘DontDestroyOnLoad’ sequence but this doesn’t work for me. Same goes if I use a sperate game object containing the script. Am I doing something wrong? Or is there another way to keep all remain health after restarting the level?
Thanks in advance.