Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 11 Next capture
2021 2022 2023
1 capture
11 Jun 22 - 11 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by rOBY GAMES · Jul 26, 2015 at 01:57 PM · healthbarcountgameoverlife

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);
     
     }
 }

alt text

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.

alt text

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.

guitext.jpg (126.6 kB)
x3.jpg (51.0 kB)
Comment
Add comment · Show 16
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Hexer · Jul 26, 2015 at 02:42 PM 0
Share

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.

avatar image rOBY GAMES · Jul 26, 2015 at 02:59 PM 0
Share

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);
     
     }
 }
avatar image rOBY GAMES · Jul 26, 2015 at 03:05 PM 0
Share

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. :-(

avatar image rOBY GAMES · Jul 26, 2015 at 03:27 PM 0
Share

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. :-(

avatar image Hexer · Jul 26, 2015 at 03:30 PM 0
Share

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"?

Show more comments

2 Replies

· Add your reply
  • Sort: 
avatar image
0

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);
 
     }
 }


Comment
Add comment · Show 12 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image rOBY GAMES · Jul 26, 2015 at 10:12 PM 0
Share

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)

avatar image Hexer · Jul 26, 2015 at 10:18 PM 0
Share

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).

avatar image Hexer · Jul 26, 2015 at 10:22 PM 0
Share

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.

avatar image rOBY GAMES · Jul 26, 2015 at 10:27 PM 0
Share

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)

avatar image Hexer · Jul 26, 2015 at 10:30 PM 0
Share

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.

Show more comments
avatar image
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.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

22 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges