I'm currently developing a game using Unity game engine and right now I'm trying to do a simple UI: place a texture (heart) on the top left corner of the screen along with the text representing the number of lifes that the player has. The text part was easy but I'm struggling with the texture, tried several methods now and can't seem to get it to work. The code I'm using is the following:
using UnityEngine;
using System.Collections;
public class Health : MonoBehaviour {
private int currentHealth;
private int startHealth;
private int maxHealth;
private Vector2 topLeftCorner;
public Texture2D heart;
// Use this for initialization
void Start () {
startHealth = 3;
maxHealth = 100;
topLeftCorner = new Vector2 (0, 0);
heart = new Texture2D (128,128);
PlaceHeart (topLeftCorner, heart);
}
void PlaceHeart (Vector2 place, Texture2D img)
{
float x = place.x * Screen.width;
float y = place.y * Screen.height;
GUI.Label(new Rect (x, y, img.width, img.height), img);
}
public void modifyHealth(int amount) {
currentHealth += amount;
// Prevent health from being < 0 or > maxHealth
currentHealth = Mathf.Clamp(currentHealth,0,maxHealth);
}
}
I assigned the variable corresponding to the texture (heart) within Unity inspector, however I'm still getting a (basic) error: "NullReferenceException: Object reference not set to an instance of an object" which I'm having a hart time to understand. Any help would be greatly appreciated.