1

我在 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

谢谢!

4

3 回答 3

2

towerPrefab在早期设置为 null,然后在第 26 行,您在为其buildPrice分配任何非 null 值之前引用其属性或字段。这将抛出一个空异常。

这条线是问题所在:

GUI.contentColor = (Player.gold >= towerPrefab.buildPrice ? Color.green : Color.red);
于 2013-06-30T04:54:52.333 回答
0

斧头已经指出了问题所在。我认为这可能会解决它:

public Tower towerPrefab = new Tower();

因为Tower类具有buildPrice您要访问的属性。

于 2013-06-30T05:17:10.543 回答
0

OP 对@Hatchet 的回复中的截图肯定显示了塔预制尚未在编辑器中设置。

它应该由其他一些代码(不起作用)设置,或者应该手动设置。您可以通过将塔预制拖到插槽上,或单击“无(塔)”右侧的小圆圈来执行此操作:这将弹出一个选择器对话框,您可以在其中选择塔预制。它显示为“塔”,因为这是它想要的变量。

顺便说一句,GUIskin 也没有设置。当您上线时,这可能会导致问题

GUI.skin = skin;

用于分配此类引用的 Unity gui 文档在这里:http ://docs.unity3d.com/Documentation/Manual/EditingReferenceProperties.html

于 2013-07-02T05:38:38.090 回答