- Home /
Working health script?
Hi I have this script that I have from another question that I asked and was wondering how to make the health bar smaller when I get hit by tagged bullets
public float maxHealth = 100.0f; // Minimum health is 0.0f (dead) public float currentHealth = 100.0f; // Players current health
 
               public Texture2D background = null;
 public Texture2D energybar = null;
 void OnGUI() {
 // Draw the background
  GUI.DrawTexture(new Rect(32.0f, 32.0f, 128.0f, 16.0f), background);
  // Draw the health/energy bar
  GUI.BeginGroup(new Rect(34.0f, 34.0f, 124.0f * (currentHealth / maxHealth), 12.0f)); GUI.DrawTexture(new Rect(0.0f, 0.0f, 124.0f, 12.0f), energybar); GUI.EndGroup(); }  
Answer by Ejlersen · Jan 01, 2011 at 12:17 AM
What do you mean by smaller? Do you mean that the GUI should be smaller? Try editing the last two parameters in the Rect's.
If you mean that when I get hit, I receive 10% of my life, so show only 90%. Then you just need to subtract currentHealth with the amount you lost.
Yeah that is what I mean but I forgot o put that I have a script but It won't work but I can't post it because I'm on my iPod. So yeah I know what you mean but when I tried it, it didn't work.(i didn't have any GUI on it though)
You need to have two textures for it to work. I know it, because that script looks a lot like one I provided a few days ago :)
Answer by SnStarr · Jan 10, 2015 at 02:27 AM
This is easier. Try this.
     using UnityEngine;
     using UnityEngine.UI;
     using System.Collections;
     
     public class PlayerHealth : MonoBehaviour 
     {
         public float maxHealth; //Your players max Health
         public float curHealth;  //Your players current health
         public Scrollbar healthBar;  //Unity UI Scrollbar Image named healthBar
     
     void Update()
      {
         //Call HealthBar function, pass it a 0 to avoid object reference error
         HealthBar(0); 
      }
        //The HealthBar function
         public void HealthBar(float adj) 
      {
         //Will create a variable named percentile based on the current health divided by the max health multiplied by 100.
         float healthPercentile = ((float)curHealth / (float)maxHealth) * 100f; 
 
 //Will rescale a scrollbar set to FILL type by the percentile variable multiplied by 100.
         healthBar.size = healthPercentile / 100f; 
      }
Your answer
 
 
             Follow this Question
Related Questions
Textarea rezing in height by text 1 Answer
Gui Resize 1 Answer
Shrink GUI 1 Answer
GuiTexture above 3D objects 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                