Hello!
I’m quite new to Unity and game making in general. I’m trying to show a flat background at the left side of the screen and then make a health bar appear on it. But none of them show up. I’ve never used OnGUI() before and I’m not sure I got everything right.
What I did was write a script which I’ll post below and attach it to a new GameObject in the scene. This object has no other components. I dragged some images (I changed the “texture type” from sprite to texture) into the texture spots in this script in the inspector. Why does it not work? There are no errors nor warnings. The game runs properly. Please, tell me what I should do! Thanks
SCRIPT:
using UnityEngine;
using System.Collections;
public class HealthDisplay : MonoBehaviour {
private Vector2 pos = new Vector2 (0, 0);
private Vector2 size = new Vector2 (0, 0);
private Vector2 barPos = new Vector2 (0, 0);
private Vector2 barSize = new Vector2 (0, 0);
private float percentage = 1f;
public Texture emptyTex;
public Texture fullTex;
public Texture bgTex;
ScreenBoundsScript screenBounds;
// Use this for initialization
void Start () {
screenBounds = GameObject.Find("Manager").GetComponent<ScreenBoundsScript>();
size = new Vector2 (screenBounds.width/6f, screenBounds.height);
pos = new Vector2 (-screenBounds.width / 2f, -screenBounds.height / 2f);
barSize = new Vector2 (size.x / 1.5f, size.y / 40f);
barPos = new Vector2 (screenBounds.width / 36f, barSize.y*2f);
}
// Update is called once per frame
void Update () {
size = new Vector2 (screenBounds.width/6f, screenBounds.height);
pos = new Vector2 (-screenBounds.width / 2f, -screenBounds.height / 2f);
barSize = new Vector2 (size.x / 1.5f, size.y / 40f);
barPos = new Vector2 (screenBounds.width / 36f, barSize.y*2f);
GameObject pl = GameObject.Find ("Player");
if ( pl != null)
{
HealthScript hlth = GameObject.Find ("Player").GetComponent<HealthScript>();
if ( hlth != null)
{
percentage = (GameObject.Find ("Player").GetComponent<HealthScript> ().health)/(GameObject.Find ("Player").GetComponent<HealthScript> ().maxHealth);
}
}
}
void OnGUI() {
//draw the background:
GUI.Box(new Rect(pos.x, pos.y, size.x, size.y), bgTex);
//draw the health bar:
GUI.Box(new Rect(barPos.x, barPos.y, barSize.x, barSize.y), emptyTex);
GUI.Box(new Rect(barPos.x, barPos.y, barSize.x*percentage, barSize.y), fullTex);
}
}
[30632-bez+tytułu.gif|30632]