向IList添加元素时出现奇怪的空引用错误

时间:2016-04-10 22:36:14

标签: c# list unity3d nullreferenceexception

我有一个非常令人困惑的问题,空引用错误。它读作:

NullReferenceException: Object reference not set to an instance of an object
GameHandler.Update () (at Assets/Scripts/GameHandler.cs:33)

这是冗长的背景:

C#

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class GameHandler : MonoBehaviour {
public GameObject canvas;

IList<GameObject> selected;
GameObject[] troopObjects;
bool isSelecting = false;
Vector3 mousePosition1;

void Update() {
    // If we press the left mouse button, save mouse location and begin selection
    if (Input.GetMouseButtonDown(0)) {
        isSelecting = true;
        mousePosition1 = Input.mousePosition;
        if(selected != null) {
            foreach (GameObject selectedTroop in selected) {
                selectedTroop.transform.GetChild(0).gameObject.SetActive(false);
            };
        };
        selected = null;
    };
    // If we let go of the left mouse button, end selection
    if (Input.GetMouseButtonUp(0)) {
        isSelecting = false;
    };
    if (isSelecting) {
        troopObjects = GameObject.FindGameObjectsWithTag("Troop");
        foreach (GameObject troop in troopObjects) {
            if (IsWithinSelectionBounds(troop)) {
                selected.Add(troop);
                troop.transform.GetChild(0).gameObject.SetActive(true);
            };
        };
    };
    if (selected != null) {

    };

}
// Use this for initialization
void Start() {
    canvas.SetActive(false);
}

void OnGUI() {
    if (isSelecting) {
        // Create a rect from both mouse positions
        var rect = Utils.GetScreenRect(mousePosition1, Input.mousePosition);
        Utils.DrawScreenRect(rect, new Color(0.8f, 0.8f, 0.95f, 0.25f));
        Utils.DrawScreenRectBorder(rect, 2, new Color(0.8f, 0.8f, 0.95f));
    }
}

public bool IsWithinSelectionBounds(GameObject gameObject) {
    if (!isSelecting)
        return false;

    var camera = Camera.main;
    var viewportBounds = Utils.GetViewportBounds(camera, mousePosition1, Input.mousePosition);
    return viewportBounds.Contains(camera.WorldToViewportPoint(gameObject.transform.position));
}
}

现在问题代码似乎就在这里:

if (isSelecting) {
    troopObjects = GameObject.FindGameObjectsWithTag("Troop");
    foreach (GameObject troop in troopObjects) {
        if (IsWithinSelectionBounds(troop)) {
            selected.Add(troop);
            troop.transform.GetChild(0).gameObject.SetActive(true);
        };
    };
};

错误引用的是:

selected.Add(troop);

它说“troop”是一个空引用。现在,当我删除这行代码时,其余的工作正常。这没有任何意义,因为在问题代码之后,有这样的:

troop.transform.GetChild(0).gameObject.SetActive(true);

使用相同的“部队”参考。我很乐意在这个方面给予一些帮助,因为它让我难过。如果需要任何额外信息,请告诉我。

1 个答案:

答案 0 :(得分:-1)

您正在使实例无效,然后根据某些条件尝试将元素添加到NULL对象。那不对。

请更改此行:

selected = null;

到此:

selected.Clear();

并在开头实例化列表:

void Update() {
selected = new List<GameObject>();