So I have a jscript that’s keeping tabs of “playerhp” and it displays as a guitext. Well I have some graphics (5) that I would like to use instead of text, and as the “playerhp” drops or increases in 20% increments, I want it to trigger the image to change to the proper image. (I’m using five bolts, when the player is at 80-100%; four bolts from 60-79%; etc) however, I don’t know where to start. Can anyone point me in the right direction, or shoot a sample snippet my way?
My pseudo would look something like this (without knowing what to do, specifically):
if playerhp > 80%
show 5bolt
elseif playerhp > 60%
show 4bolt
elseif playerhp > 40%
show 3bolt
elseif playerhp > 20%
show 2bolt
else
show 1bolt
Just attach your textures to the Textures variable and they will turn into the “bolts” you need.
By changing VisibleCount the script shows only the visible number of images. The exact number (related to a percentage of health) you should calculate somewhere else and set from the outside.
By attaching the skin to ButtonSkin you could style the buttons. You could even react on clicking of the the particular texture (check out the ClickHandler method).
Enjoy!
using UnityEngine;
/// <summary>
/// Health GUI example
/// </summary>
/// <remarks>Author: Danko Kozar</remarks>
public class HealthGui : MonoBehaviour
{
public Rect ButtonSize = new Rect(0, 0, 128, 128);
public GUISkin ButtonSkin;
public float GapSize = 10;
public Texture2D[] Textures;
public int VisibleCount = 5;
private Rect _menuBounds;
void Update()
{
VisibleCount = Mathf.Clamp(VisibleCount, 0, Textures.Length); // restricting VisibleCount
}
void OnGUI()
{
int count = Textures.Length;
float width = ButtonSize.width * count + GapSize * Mathf.Max(count-1, 0); // sum of button widths and gaps;
float height = ButtonSize.height; // the height of a single button
float x = (Screen.width - width)*0.5f;
float y = (Screen.height - height)*0.5f;
_menuBounds = new Rect(x, y, width, height);
if (null != ButtonSkin) // apply skin
GUI.skin = ButtonSkin;
GUI.BeginGroup(_menuBounds); // group start
int index = 0;
foreach (Texture2D texture in Textures)
{
if (index >= VisibleCount)
break;
if (GUI.Button(
new Rect((ButtonSize.width + GapSize) * index, 0, ButtonSize.width, ButtonSize.height),
new GUIContent(string.Empty, texture))) // relative to group, so x and y start from 0
{
ClickHandler(index);
}
index++;
}
GUI.EndGroup(); // group end
}
void ClickHandler(int index)
{
Debug.Log("Clicked button at index " + index);
}
}