- Home /
How can I change this script to use GUITexture instead of GUI number, for health display?
Goal is to make so that health gets subtracted, and results in new GUItexture every 5% of health drop(as a health bar), but currently, I have a number GUI set up. OR if a scaling bar is more optimized, I may do that.
@script ExecuteInEditMode()
var hitPoints : int;
var painSound : AudioClip;
var die : AudioClip;
var deadReplacement : Transform;
var mySkin : GUISkin;
var explShake : GameObject;
private var radar : GameObject;
private var maxHitPoints : int;
var damageTexture : Texture;
private var time : float = 0.0;
private var alpha : float;
private var callFunction : boolean = false;
function Start(){
maxHitPoints = hitPoints;
alpha = 0;
}
function Update(){
if (time > 0){
time -= Time.deltaTime;
}
alpha = time;
}
function PlayerDamage (damage : int) {
if (hitPoints < 0.0)
return;
// Apply damage
hitPoints -= damage;
audio.PlayOneShot(painSound, 1.0 / audio.volume);
time = 2.0;
function OnGUI () {
GUI.skin = mySkin;
GUI.contentColor = Color.red;
GUI.Label (Rect(40, Screen.height - 50,60,60)," Health: ");
GUI.Label (Rect(100, Screen.height - 50,60,60),"" +hitPoints);
GUI.color = Color(1.0, 1.0, 1.0, alpha); //Color (r,g,b,a)
GUI.DrawTexture(new Rect(0,0,Screen.width, Screen.height), damageTexture);
Answer by Hivemind · Jan 14, 2013 at 05:25 AM
I recommend creating an actual GUITexture in your scene instead of using GUI.DrawTexture. You can also store a rectangle for the current health bar instead of making one every OnGUI call (every frame). I would do this for all rectangles in OnGUI.
To update your health bar, I would do the following ...
var MAX_HITPOINTS = 100;
var healthBarOrigWidth : int;
var healthBar : GUITexture;
function PlayerDamage (damage : int) {
//Somewhere in this function
healthBar.width = healthBarOrigWidth * (hitPoints/MAX_HITPOINTS);
}
This way you don't create rectangles every frame in the OnGUI function. The health bar updates when PlayerDamage() is called.
I am getting this error: $$anonymous$$issingFieldException: Field 'UnityEngine.GUITexture.width' not found
Generally, you can figure out your problem when it is as simple as a variable/property not found.
http://docs.unity3d.com/Documentation/ScriptReference/GUITexture.html
So you can check on the documentation of GUITexture and see if it exists. In our case, it doesn't. It is inside pixelInset. So basically, someGuiTexture.pixelInset.width.
Hope this helps.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Health script and damage script dont work. 2 Answers
Where too learn unityscript? 3 Answers
Save Player Health and stats 1 Answer
Semicolon error using JS 1 Answer