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

Strange Null Reference Error while adding element to IList

我遇到了一个非常令人困惑的空引用错误问题。它显示为:

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);

它使用相同的 "troop" 引用。我很乐意在这方面获得一些帮助,因为它让我感到难过。如果需要任何额外信息,请告诉我。

确定部队为空,未选中?您上面的代码检查已选择,如果它不为空,则将其清空。

selected = null;

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

请更改此行:

selected = null;

对此:

selected.Clear();

并在开头实例化列表:

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