0

在 Unity 3D 中开发 FPS 游戏时出现错误

NullReferenceException:对象引用未设置为对象 Node.OnDrawGizmos () 的实例(在 Assets/Node.cs:14)

它之前工作正常,但是当我向节点添加层时,我得到了这个错误。

查看完整代码

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

public class Node : MonoBehaviour {

public List<GameObject> neighours = new List<GameObject>();

public float nodeRadius = 50.0f;
public LayerMask nodeLayerMask;
public LayerMask collisionLayerMask;

public GameObject goal;

void OnDrawGizmos() {

    Gizmos.DrawWireCube(transform.position, Vector3.one);

    foreach(GameObject neighbor in neighbors) {

        Gizmos.DrawLine(transform.position, neighbor.transform.position);
        Gizmos.DrawWireSphere(neighbor.transform.position, 0.25f);
    }

    if(goal) {

        GameObject current = gameObject;
        Stack<GameObject> path = DijkstraAlgorithm.Dijkstra(GameObject.FindGameObjectsWithTag("Node"), gameObject, goal);

        foreach(GameObject obj in path) {

            Gizmos.DrawSphere(obj.transform.position, 1.0f);
            Gizmos.color = Color.green;
            Gizmos.DrawLine(current.transform.position, obj.transform.position);
            current = obj;
        }
    }
}

[ContextMenu ("Connect Node to Neighours")]
void findNeighours() {

    neighours.Clear();
    Collider[] cols = Physics.OverlapSphere(transform.position, nodeRadius, nodeLayerMask);

    foreach(Collider node in cols) {

        if(node.gameObject != gameObject) {


        }
    }
}

}

4

1 回答 1

0

我看到findNeighours不喂neighours,所以我想你想要这样的东西:

foreach (Collider node in cols) {
    if (node.gameObject != gameObject)
        neighours.Add (node.gameObject);
}

关于OnDrawGizmos, 潜在地path并且neighours可能持有null物品。你应该检查是否是这种情况,看看为什么它充满了它null。请注意,可能删除场景中的游戏对象(而不是使用 刷新findNeighours)可能会使其保持null引用。

检查您是否定义了goal.

注意:邻居是指邻居吗?

于 2013-03-29T10:26:22.350 回答