我目前正在使用 Unity 游戏引擎开发游戏,现在我正在尝试做一个简单的 UI:在屏幕的左上角放置一个纹理(心脏)以及代表玩家生命数量的文本有。文本部分很简单,但我在纹理上苦苦挣扎,现在尝试了几种方法,但似乎无法让它发挥作用。我正在使用的代码如下:
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);
}
}
我在 Unity 检查器中分配了与纹理(心脏)相对应的变量,但是我仍然收到一个(基本)错误:“NullReferenceException: Object reference not set to an instance of an object”,我很难做到理解。任何帮助将不胜感激。