2

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.

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
user3019217
  • 335
  • 1
  • 5
  • 12

2 Answers2

0

It might be as easy as to remove the line

heart = new Texture2D (128,128);

from your code. Anything you set in the Inspector doesnt need to be created in the script.

Tom
  • 627
  • 6
  • 11
  • Had already tried that but it didn't work, it's not the issue here. – user3019217 Apr 20 '14 at 19:45
  • the thing is this line actually creates an Empty Texture2D and replaces the one you set in the editor. Can you maybe specify the line in which the error occurs? Also you might want to use GUITexture instead of Texture2D from what i read in the docs. – Tom Apr 20 '14 at 22:06
0

The code you have now won't work because you're trying to use the GUI methods which only work inside OnGui() in a place other than OnGui()

That said, you should stop using the GUI methods and use the New Unity 4.6 UI which is made of pixie dust and dreams.

Basically, you go to the GameObject menu, UI, Image. The canvas will get set up for you, screen space is perfect, just zoom out and enter a 2D view, activate the RectTransform tool (it's that square one next to scale) to position the white box, then over in the inspector you can assign a sprite (so it looks like a heart, rather than white).

Inspector