我在 Unity 中收到此错误:
NullReferenceException:对象引用未设置为对象 TowerSlot.OnGUI () 的实例(在 Assets/TowerSlot.cs:26)
我对 Unity 比较陌生,无法弄清楚这个错误来自哪一行(我假设是 26 行),我不知道什么是空的。如果有人可以帮助向我解释如何理解错误所指向的内容以及我需要做什么,将不胜感激。
TowerSlot.cs:
using UnityEngine;
using System.Collections;
public class TowerSlot : MonoBehaviour {
public GUISkin skin = null;
bool gui = false;
// Tower prefab
public Tower towerPrefab = null;
void OnGUI() {
if (gui) {
GUI.skin = skin;
// get 3d position on screen
Vector3 v = Camera.main.WorldToScreenPoint(transform.position);
// convert to gui coordinates
v = new Vector2(v.x, Screen.height - v.y);
// creation menu for tower
int width = 200;
int height = 40;
Rect r = new Rect(v.x - width / 2, v.y - height / 2, width, height);
GUI.contentColor = (Player.gold >= towerPrefab.buildPrice ? Color.green : Color.red);
GUI.Box(r, "Build " + towerPrefab.name + "(" + towerPrefab.buildPrice + " gold)");
// mouse not down anymore and mouse over the box? then build the tower
if (Event.current.type == EventType.MouseUp &&
r.Contains(Event.current.mousePosition) &&
Player.gold >= towerPrefab.buildPrice) {
// decrease gold
Player.gold -= towerPrefab.buildPrice;
// instantiate
Instantiate(towerPrefab, transform.position, Quaternion.identity);
// disable gameobject
gameObject.SetActive(false);
}
}
}
public void OnMouseDown() {
gui = true;
}
public void OnMouseUp() {
gui = false;
}
}
此外,我正在尝试在此处遵循本教程http://makeagame.info/unity-tower-defense-game-step-4-scripting
谢谢!