I’m fairly new to Unity & C#, i’ve made a basic Flappy Bird type clone which runs perfect on WebGL, Windows & Android. I have decided to spruce it up a little and add in levels - after reaching a set score on each level the player advances. This component runs well as expected, I also want to implement a life system where if the player dies then it should decrease life by 1, so 3 lives max each time you die that value decreases by -1. Upon reaching -1 lives then the game will load up a game over screen and then head to the menu.
What my problem is, is I can’t for the life of me figure out how to decrease my life. I have tried adding it to the OnCollisionEnter2D(); part of the script by using lives -= 1; it doesn’t work, and if i add to the void Die() it also doesn’t work.
The only way I have got this to work is by using an OnGUI code, is there anyway i can use it via using Unitys UI like i have done for a score and highscore?
My code is as follows…
using UnityEngine;
using UnityEngine.UI;
public class Playera : MonoBehaviour
{
// The force which is added when the player jumps
// This can be changed in the Inspector pannel
public Vector2 jumpForce = new Vector2(0,300);
// Lives settings
public float lives = 3;
public Text livesText;
void Start (){
// Set Live GUI
if(livesText.name == "livesText")
{
livesText.text = "Lives:" + lives;
}
}
// Update is called once per frame
void Update ()
{
// Jump
if (Input.GetKeyUp("space"))
{
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
GetComponent<Rigidbody2D>().AddForce(jumpForce);
GetComponent<AudioSource>().Play(); // Plays Audio clip attached to GameObject
}
// Touch Controls
if (Input.GetMouseButtonUp(0))
{
GetComponent<Rigidbody2D>().velocity = Vector2.zero;
GetComponent<Rigidbody2D>().AddForce(jumpForce);
GetComponent<AudioSource>().Play(); // Plays the audio clip that is attached to gameobject
}
// Die by being off screen
Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
if (screenPosition.y > Screen.height || screenPosition.y < 0)
{
Die ();
}
// Exit Game
if (Input.GetKey("escape"))
{
Application.Quit();
}
// Save Lives
PlayerPrefs.SetFloat ("Lives", lives);
PlayerPrefs.Save();
}
// Die by collision
void OnCollisionEnter2D(Collision2D other)
{
Die();
}
// What happens when Die is called
void Die()
{
lives -= 1;
Application.LoadLevel("Level0");
}
}
If i was to use the OnGUI code i would take out the void Start function and replace with
void OnGUI ()
{
GUI.color = Color.black;
GUILayout.Label(" Lives: " + lives.ToString());
}
Any help is appreciated