Hi everyone! I am trying to make 3 lives for the player, each time a ball hit him, hearts decrease and disappear till the end of the game.
I have two problems:
When the ball hit the player, hearts still remaining no one disappear
I am using LoadLevel, so when some heart disappear it appear again when reloading the level, how to not restore hearts total amount. I tried DontDestroy function, but didn’t work for me.
Here is few lines of the code
For your 1st issue ; How are defined h1, h2, h3 ? If those are UI images (attached to an UI canvas) then it should work with “hN.enabled (false);” (remove the “.gameObject”)
For the 2nd issue (passing a variable from scene to scene) you can use DontDestroyOnLoad() as you said, tho you need your script to be either a monobehavior derived class or attached to a gameObject ;
public void Awake()
{
DontDestroyOnLoad(this.gameObject);
}
Of course if your script is on the player itself and you destroy him when you exit your scene it’s not gonna work (simply put the UI update in another script / on an other empty gameobject)
All in all your script should look like ;
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
// Attach to an empty GameObject
// To initialize script on a new scene, add updateHealthUI() in the Awake or Start Method of your player
// Then just use this script in your OnCollision method using thisScript.Health --
public class UpdateHealthUI : MonoBehaviour // MonoBehaviour
{
// Insert your 3 hearts images in the Unity Editor
[SerializeField] private Image h1, h2, h3;
// Create an array because we're lazy
private Image[] images;
// Gameover
[SerializeField] private Image gameOver;
// A private variable to keep between scenes
[SerializeField] private int health = 3;
// Now we define Get / Set methods for health
// In case we Set health to a different value we want to update UI
public int Health { get { return health; } set { if (health != Health) health = Health; updateHealthUI(); } }
public void Awake()
{
DontDestroyOnLoad(this.gameObject);
images = new Image[] { h1, h2, h3 };
}
private void updateHealthUI()
{
for(int i = 0; i < images.Length;i++)
{
// Hide all images superior to the newHealth
if (i >= health)
images*.enabled = false;*
else images*.enabled = true;* } // Game Over if (health == 0) { gameOver.enabled = true; ; Time.timeScale = 0; } } }
You can use void OnSceneLoaded(Scene scene, LoadSceneMode mode) to check when a level is loaded and then call your method CheckHealth(); inside. Note that Health would have to be declared as static so that it’s value persist during change of scenes.
As for why the hearts are not disapearing when a ball hits the player i don’t know, is hard to say by just looking at the piece of code you provided, the best i can say to you is to Debug, see if the object name is actually what you expect and things like that.