• 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 wmmayfield · Jan 31, 2019 at 04:26 PM · counterhealthbar

My attached script is not working. Can someone help with my coding?

I'm trying to do two things with the attached script: first to get the slider and text to reflect the health of the player. The health text shows the full amount of health(3) however it does not change with health as indicated by the Debug.Log("Health: " + health). Also, the lines of code under Update are not functioning. I've attached the HealthBar script to an empty gameObject. The slider and the text are also attached and the total health int is also attached in the gameObject named HealthBar.

The second issue is that I am trying to get DontDestroyOnLoad to work. I'm new to Unity and gaming so any help would br really apprceciated.

using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement;

public class Healthbar: MonoBehaviour {

 public int health;
 public Slider slider;
 public Text text;

 /*void Awake()
 {
     GameObject[] objs = GameObject.FindGameObjectsWithTag("Health");

     if (objs.Length > 1)
     {
         Destroy(this.gameObject);
     }

     DontDestroyOnLoad(this.gameObject);
 }*/
 void Update()
 {
     Debug.Log("update");
     slider.value = health; 
     text.text ="Health : " + health;

     /*if(health <= 0)
         {
             Debug.Log("Game Over");
         }*/
 }



 void OnTriggerEnter (Collider other)
 {
     if (gameObject.tag == "Hazards") 
     {    
         
         health = health - 1; 
         Debug.Log ("Health: " + health);
         Destroy (other.gameObject);

         //SceneManager.LoadScene (SceneManager.GetActiveScene ().buildIndex);



     }
 }

}

Comment
Add comment
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

3 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by Tasarran · Jan 31, 2019 at 04:48 PM

slider.value is a float, not an int. Either change health to be a float or 'cast' it thusly:

 slider.value = (float) health;

You're also going to have a similar problem on the next line; health is an int, you can't add a string and an int. It should be:

 text.text = "Health : " + health.ToString();

Yes, completely different ways of changing one data type into another, this isn't just for example purposes. For simple data types, you can just (type) cast them, but for strings, you need to use int.ToString() (in this case).

Comment
Add comment · Show 9 · 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 wmmayfield · Jan 31, 2019 at 04:57 PM 0
Share

Thanks for yoru help. I made the changes as you suggested but it still fails to work. Any thoughts on the DontDestroyOnLoad?

avatar image Tasarran · Jan 31, 2019 at 05:41 PM 0
Share

Is your Slider set up with a $$anonymous$$in and $$anonymous$$ax, and is the Whole Numbers setting turned on? If you haven't set that up, your default Slider only goes from 0.0-1.0, I believe...

avatar image wmmayfield · Jan 31, 2019 at 05:46 PM 0
Share

slider is set as you suggest and ther is still no movement. It seems like it is detached from the action of the scene. The text loads the slider to health of 3 but as the scene runs the debug.log counts and calls game over correctly. The slider just sits there.

avatar image wmmayfield · Jan 31, 2019 at 05:50 PM 0
Share

Tried your suggestion and all that did was to shrink the health bar. Am I missing anything with regards to connecting the slider to the script?

avatar image Tasarran · Jan 31, 2019 at 06:01 PM 0
Share

What happens if you change that to

 slider.value = 1;

Show more comments
avatar image
0

Answer by Magso · Jan 31, 2019 at 04:56 PM

Firstly where you have Destroy and DontDestroyOnLoad, just use (gameObject). 'this' refers to the script itself so 'Destroy(this)' would remove the script's own component.

Secondly the if statement checking the tag is checking the gameObejcts own tag, not the hazard's tag. You can use

 if (other.tag == "Hazards")
 //or
 if (other.gameObject.tag == "Hazards")

Thirdly, just a nitpick but

 health = health - 1; 
 //can be written as
 health--;

When you plus or minus 1, it's either ++ or -- , if it's not just 1 you can use

 health += 2f;
 //and 
 health -= 4.2635f;

The f at the end stands for float.

Comment
Add comment · Show 2 · 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 wmmayfield · Jan 31, 2019 at 05:10 PM 0
Share

Thanks for the suggestions. They are working somewhat. The Debug.Log("Health: " + health) is correctly counting and calling GameOver. However the health bar shows no movement or change in number. It always shows 3.

I'm open to additional thoughts and suggestions.

avatar image Magso wmmayfield · Jan 31, 2019 at 05:46 PM 0
Share

Tasarran mentioned the slider's value has to be between 0 and 1 so

 public float health;
 slider.value = health/3;

should work for that, but make sure the health variable is a float, not an integer.

avatar image
0

Answer by AnOrdinarySandwich · Feb 01, 2019 at 01:47 AM

Don't worry about changing your health to a float if that's not what you need. The only real issue is making sure the slider's max and min values are set. I'm assuming minimum health is 0, so slider.minValue should be defaulted to 0 ( but it doesn't hurt to assign it anyway). Then, set maxValue to whatever the maximum health is, and after, keep updating the slider.value = health.

For DontDestroyOnLoad, firstly, it must be on a root gameObject (in the hierarchy) or on a component on a root gameObject.



No offense @Tasarran, but int's don't need to be cast to float, they'll auto convert. Additionally, int's and float don't require ToString() to append to a string, they'll auto-convert.

void Start()
{
   int ten=10;
   float d = ten;
   string output = "x = "+ten + " : " + d;
}

This code gives me no errors.

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

100 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 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 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 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 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

GUI Help, timer and counter 1 Answer

How to give a bonus every 1000 points? 2 Answers

Dual Timer Problems 1 Answer

Using Time.deltaTime as time counter. 1 Answer

deactivate un-used zeros 2 Answers


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