我正在使用Unity游戏引擎开发游戏,现在我正在尝试做一个简单的UI:在屏幕的左上角放置一个纹理(心脏)以及代表玩家生命数量的文本具有 . 文本部分很容易,但我正在努力与纹理,现在尝试了几种方法,似乎无法让它工作 . 我正在使用的代码如下:
使用UnityEngine;
使用System.Collections;
公共课 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:对象引用没有设置为对象的实例”我有一个哈特时间到了解 . 任何帮助将不胜感激 .
2 回答
它可能就像删除线一样容易
从你的代码 . 您在Inspector中设置的任何内容都不需要在脚本中创建 .
你现在赢得的代码't work because you'试图在
OnGui()
以外的地方使用GUI
方法only work inside OnGui()也就是说,你应该停止使用GUI方法并使用由小精灵尘埃和梦想组成的the New Unity 4.6 UI .
基本上,您可以转到GameObject菜单,UI,Image . 画布将为您设置,屏幕空间是完美的,只需缩小并输入2D视图,激活RectTransform工具(它是刻度旁边的那个正方形)来定位白色框,然后在检查器中指定您可以分配一个精灵(所以它看起来像一颗心,而不是白色) .