- Home /
problem count life of the player.
Hello!
I have three scripts. 1 is (ContoVita) that counts the screw from three to zero added to a GUITEXT. All written by me is added in the inspector.
using UnityEngine;
using System.Collections;
public class Contovita : MonoBehaviour {
public static int temp = 5;
void Awake () {
guiText.text = ""+3;
print(temp);
}
}
The second script is (LevelManager) that allows the player to respawn when life ends. (HealthBar). In the script (LevelManager) on the line (15, 16. Then at 133, up to 138) I added the change.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System;
using UnityEditor;
public class LevelManager : MonoBehaviour
{
public static LevelManager Instance { get; private set; }
public Player Player { get; private set; }
public CameraController Camera { get; private set; }
public TimeSpan RunningTime { get { return DateTime.UtcNow - _started; } }
public static int life = 3;
public static int temp = 5;
public int CurrentTimeBonus
{
get
{
var secondDifference = (int) (BonusCutoffSeconds - RunningTime.TotalSeconds);
return Mathf.Max(0, secondDifference) * BonusSecondMultiplier;
}
}
private List<Checkpoint> _checkpoints;
private int _currentCheckpointIndex;
private DateTime _started;
private int _savedPoints;
public Checkpoint DebugSpawn;
public int BonusCutoffSeconds;
public int BonusSecondMultiplier;
public void Awake()
{
_savedPoints = GameManager.Instance.Points;
Instance = this;
}
public void Start ()
{
_checkpoints = FindObjectsOfType<Checkpoint>().OrderBy(t => t.transform.position.x).ToList();
_currentCheckpointIndex = _checkpoints.Count > 0 ? 0 : -1;
Player = FindObjectOfType<Player>();
Camera = FindObjectOfType<CameraController>();
_started = DateTime.UtcNow;
var listeners = FindObjectsOfType<MonoBehaviour>().OfType<IPlayerRespawnListener>();
foreach (var listener in listeners)
{
for (var i = _checkpoints.Count - 1; i >= 0; i--)
{
var distance = ((MonoBehaviour)listener).transform.position.x - _checkpoints[i].transform.position.x;
if (distance < 0)
continue;
_checkpoints[i].AssignObjectToCheckpoint(listener);
break;
}
}
#if UNITY_EDITOR
if (DebugSpawn != null)
DebugSpawn.SpawnPlayer(Player);
else if (_currentCheckpointIndex != -1)
_checkpoints[_currentCheckpointIndex].SpawnPlayer(Player);
#else
if (_currentCheckpointIndex != -1)
_checkpoints[_currentCheckpointIndex].SpawnPlayer(Player);
#endif
}
public void Update ()
{
var isAtLastCheckpoint = _currentCheckpointIndex + 1 >= _checkpoints.Count;
if (isAtLastCheckpoint)
return;
var distanceToNextCheckpoint = _checkpoints[_currentCheckpointIndex + 1].transform.position.x - Player.transform.position.x;
if (distanceToNextCheckpoint >= 0)
return;
_checkpoints[_currentCheckpointIndex].PlayerLeftCheckpoint();
_currentCheckpointIndex++;
_checkpoints[_currentCheckpointIndex].PlayerHitCheckpoint();
GameManager.Instance.AddPoints(CurrentTimeBonus);
_savedPoints = GameManager.Instance.Points;
_started = DateTime.UtcNow;
}
public void GotoNextLevel(string levelName)
{
StartCoroutine(GotoNextLevelCo(levelName));
}
private IEnumerator GotoNextLevelCo(string levelName)
{
Player.FinishLevel();
GameManager.Instance.AddPoints(CurrentTimeBonus);
FloatingText.Show("Level Complete!", "CheckpointText", new CenteredTextPositioner(.2f));
yield return new WaitForSeconds(1);
FloatingText.Show(string.Format("{0} points!", GameManager.Instance.Points), "CheckpointText", new CenteredTextPositioner(.1f));
yield return new WaitForSeconds(5f);
if (string.IsNullOrEmpty(levelName))
Application.LoadLevel("StartScreen");
else
Application.LoadLevel(levelName);
}
public void KillPlayer()
{
StartCoroutine(KillPlayerCo());
}
private IEnumerator KillPlayerCo()
{
Player.Kill();
Camera.IsFollowing = false;
yield return new WaitForSeconds(2f);
if(life <= 0){
HealthBar.life --;
GameObject.Find("Vita3").guiText.text = ""+HealthBar.life;
print("YOU NOW HAVE " + HealthBar.life + "life");
Application.LoadLevel("gameover");
}
Camera.IsFollowing = true;
if (_currentCheckpointIndex != -1)
_checkpoints[_currentCheckpointIndex].SpawnPlayer(Player);
_started = DateTime.UtcNow;
GameManager.Instance.ResetPoints(_savedPoints);
}
}
the third script (HealthBar). With the modification on the line (11,12, then 22, and 29).
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System;
using UnityEditor;
public class HealthBar : MonoBehaviour
{
public static int life = 0;
public static int temp = 5;
public Player Player;
public Transform ForegroundSprite;
public SpriteRenderer ForegroundRenderer;
public Color MaxHealthColor = new Color(255 / 255f, 63 / 255f, 63 / 255f);
public Color MinHealthColor = new Color(64 / 255f, 137 / 255f, 255 / 255f);
void Start()
{
life += 3;
}
// Update is called once per frame
public void Update ()
{
HealthBar.life -= 1;
var healthPercent = Player.Health / (float) Player.MaxHealth;
ForegroundSprite.localScale = new Vector3(healthPercent, 1, 1);
ForegroundRenderer.color = Color.Lerp(MaxHealthColor, MinHealthColor, healthPercent);
}
}
Now I'm editing the two scripts (LevelManager) is (HealthBar) to load the level Gameover when (HealthBar) is performed three times.
When I start the game to test it does not work, the number (X 3) remains fixed even die itself 10 times, not counting down. Then no charge level (gameover). some advice? I hope I was clear in describing the problem. Thank You.
The problem is that in your first script you don't reduce the life for Level$$anonymous$$anager.life. Level$$anonymous$$anager.life will never reach 0 because of this.
in your Level$$anonymous$$anager script change at line 133. if(life <=0)
to if(Health.life <=0)
. that should do the trick. You will actually be checking the lives from the Health script ins$$anonymous$$d of the lives of the Level$$anonymous$$anager.
1 more problem, you will encounter that on play your lives will probably immediatly evaporate, due to the fact that we set the Health.life-=1;
in the void Update. We only want to call this line of code when something occures and so because of that reduce the lives with 1. (with that I mean the method your player should lose a life)
EDIT : OR, just only add a line called Level$$anonymous$$anager.life -=1;
in your third script under Healthbar.life -=1;
But you still have to decide on the method of calling that line. because I suppose we don't want to lose 3lives in 3 frames.
Hello Exer.
thanks for your help. :-)
I edited the first script in this way: line 12.
print(Level$$anonymous$$anager.temp);
using UnityEngine;
using System.Collections;
public class Contovita : $$anonymous$$onoBehaviour {
public static int temp = 5;
void Awake () {
guiText.text = ""+3;
print(Level$$anonymous$$anager.temp);
}
}
Now when I start the game after the bar ends, now the charge level gameover.
I also modified (Level$$anonymous$$anager) line 133.
if (HealthBar.life <= 0)
but still not working.
can you help me? I do not know how to solve. I think it's easy problem but do not know what. :-(
ok I added Level$$anonymous$$anager.life - = 1; Below this line: HealthBar.life - = 1; in the third script (HealthBar).
But that does not change. When you start the game, when the player dies, the charge level immediately gameover. Now I'm confused. :-(
Now when I start the game after the bar ends, now the charge level gameover.
Do you mean that, when you start the game it will immediatly goes to the scene "gameover"?
Answer by rOBY GAMES · Jul 26, 2015 at 09:46 PM
Contovita:
using UnityEngine;
using System.Collections;
public class Contovita : MonoBehaviour {
public static int temp = 3;
void Update () {
guiText.text = LevelManager.life.ToString();
print(temp);
}
}
LevelManager:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System;
using UnityEditor;
public class LevelManager : MonoBehaviour
{
public static LevelManager Instance { get; private set; }
public Player Player { get; private set; }
public CameraController Camera { get; private set; }
public TimeSpan RunningTime { get { return DateTime.UtcNow - _started; } }
public static int life = 3;
public static int temp = 3;
public int CurrentTimeBonus
{
get
{
var secondDifference = (int) (BonusCutoffSeconds - RunningTime.TotalSeconds);
return Mathf.Max(0, secondDifference) * BonusSecondMultiplier;
}
}
private List<Checkpoint> _checkpoints;
private int _currentCheckpointIndex;
private DateTime _started;
private int _savedPoints;
public Checkpoint DebugSpawn;
public int BonusCutoffSeconds;
public int BonusSecondMultiplier;
public void Awake()
{
_savedPoints = GameManager.Instance.Points;
Instance = this;
}
public void Start ()
{
_checkpoints = FindObjectsOfType<Checkpoint>().OrderBy(t => t.transform.position.x).ToList();
_currentCheckpointIndex = _checkpoints.Count > 0 ? 0 : -1;
Player = FindObjectOfType<Player>();
Camera = FindObjectOfType<CameraController>();
_started = DateTime.UtcNow;
var listeners = FindObjectsOfType<MonoBehaviour>().OfType<IPlayerRespawnListener>();
foreach (var listener in listeners)
{
for (var i = _checkpoints.Count - 1; i >= 0; i--)
{
var distance = ((MonoBehaviour)listener).transform.position.x - _checkpoints[i].transform.position.x;
if (distance < 0)
continue;
_checkpoints[i].AssignObjectToCheckpoint(listener);
break;
}
}
#if UNITY_EDITOR
if (DebugSpawn != null)
DebugSpawn.SpawnPlayer(Player);
else if (_currentCheckpointIndex != -1)
_checkpoints[_currentCheckpointIndex].SpawnPlayer(Player);
#else
if (_currentCheckpointIndex != -1)
_checkpoints[_currentCheckpointIndex].SpawnPlayer(Player);
#endif
}
public void Update ()
{
var isAtLastCheckpoint = _currentCheckpointIndex + 1 >= _checkpoints.Count;
if (isAtLastCheckpoint)
return;
var distanceToNextCheckpoint = _checkpoints[_currentCheckpointIndex + 1].transform.position.x - Player.transform.position.x;
if (distanceToNextCheckpoint >= 0)
return;
_checkpoints[_currentCheckpointIndex].PlayerLeftCheckpoint();
_currentCheckpointIndex++;
_checkpoints[_currentCheckpointIndex].PlayerHitCheckpoint();
GameManager.Instance.AddPoints(CurrentTimeBonus);
_savedPoints = GameManager.Instance.Points;
_started = DateTime.UtcNow;
}
public void GotoNextLevel(string levelName)
{
StartCoroutine(GotoNextLevelCo(levelName));
}
private IEnumerator GotoNextLevelCo(string levelName)
{
Player.FinishLevel();
GameManager.Instance.AddPoints(CurrentTimeBonus);
FloatingText.Show("Level Complete!", "CheckpointText", new CenteredTextPositioner(.2f));
yield return new WaitForSeconds(1);
FloatingText.Show(string.Format("{0} points!", GameManager.Instance.Points), "CheckpointText", new CenteredTextPositioner(.1f));
yield return new WaitForSeconds(5f);
if (string.IsNullOrEmpty(levelName))
Application.LoadLevel("StartScreen");
else
Application.LoadLevel(levelName);
}
public void KillPlayer()
{
StartCoroutine(KillPlayerCo());
}
private IEnumerator KillPlayerCo()
{
Player.Kill();
Camera.IsFollowing = false;
yield return new WaitForSeconds(2f);
if(HealthBar.life <= 0){
HealthBar.life --;
GameObject.Find("Vita3").guiText.text = ""+HealthBar.life;
print("YOU NOW HAVE " + HealthBar.life + "life");
Application.LoadLevel("gameover");
}
Camera.IsFollowing = true;
if (_currentCheckpointIndex != -1)
_checkpoints[_currentCheckpointIndex].SpawnPlayer(Player);
_started = DateTime.UtcNow;
GameManager.Instance.ResetPoints(_savedPoints);
}
}
HealthBar:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System;
using UnityEditor;
public class HealthBar : MonoBehaviour
{
public static int life = 0;
public static int temp = 3;
public Player Player;
public Transform ForegroundSprite;
public SpriteRenderer ForegroundRenderer;
public Color MaxHealthColor = new Color(255 / 255f, 63 / 255f, 63 / 255f);
public Color MinHealthColor = new Color(64 / 255f, 137 / 255f, 255 / 255f);
void Start()
{
life += 3;
HealthBar.life -= 1;
LevelManager.life -= 1;
}
// Update is called once per frame
public void Update ()
{
var healthPercent = Player.Health / (float) Player.MaxHealth;
ForegroundSprite.localScale = new Vector3(healthPercent, 1, 1);
ForegroundRenderer.color = Color.Lerp(MaxHealthColor, MinHealthColor, healthPercent);
}
}
I created the script reduces life with a collider (trigger is - true) start the game after the first death that occurs when the entire life bar goes to zero, am I getting this on the console: NOW YOU HAVE -8life UnityEngine.$$anonymous$$onoBehaviour: print (Object) c__Iterator2D: $$anonymous$$oveNext () (at Assets / x ninja / Code / Level$$anonymous$$anager.cs: 136)
And the guiText will show you -8? This can be solved by saying.
if(Health.life <0){
Health.life = 0
}
This has to be set in the void update (doesnt matter which script).
also remove this code from line 134
HealthBar.life --;
Due to this, you will keep decrement HealthBar.life which give you that weird number -8.
I included this if (HealthBar.life <0) {HealthBar.life = 0;} void in Update (HealthBar).
now on the console appears to me: -1 YOU NOW HAVE -1life UnityEngine.$$anonymous$$onoBehaviour: print (Object) c__Iterator2D: $$anonymous$$oveNext () (at Assets / x ninja / Code / Level$$anonymous$$anager.cs: 136)
if you did remove the HealthBar.life --;
at line 134 of Level$$anonymous$$anager.
Then it should go to 0. Tell me if you did this and if it stays -1 or changed to 0.
Answer by Hexer · Jul 26, 2015 at 09:58 PM
If the score stays 2 and we don't go to the gameover scene, everything is fine. The code works. The only thing left to do is to decide when to call Health.life -=1;
(change for convovita LevelManager to Health, this will make things easier)
So go on and delete that 2 line of code from the void Start ( we dont need HealthBar.life -=1; and LevelManager.life -=1; in the script "Healthbar" anymore).
Go to Unity, create a 3d Object (cube). Click on the cube in the hierarchy, go to the inspector and change in the boxcollider, isTrigger to check = true. And attach the tag "Player" to the player.
We are going to add this script to that cube.
using UnityEngine;
using System.Collections;
public class ReducesLife : MonoBehaviour {
void OnTriggerEnter (Collider col)
{
if (col.tag == "Player")
{
Health.life -= 1;
}
}
}
Now everytime the player walks through that cube the Health will be reduced by 1. We succesfully made a game mechanic on how to reduce the lives for the player.
Your answer
![](https://koobas.hobune.stream/wayback/20220611233116im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Spinning Pointer that reacts when health drops 0 Answers
Regain health on GUI 2 Answers
Counting on Unity iphone. 1 Answer
to load gameover scene when life is equal to null 1 Answer
How to make a camera's background be another camera's veiw 1 Answer