我在Unity3D中出现此错误 - NullReferenceException:对象引用未设置为对象的实例

时间:2013-03-29 06:52:52

标签: c# unity3d frame-rate

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


        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

我看到findNeighours没有提供neighours,所以我想你想要这样的东西:

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

关于OnDrawGizmos,可能pathneighours可能持有null项。您应该检查是否是这种情况,并查看它为什么填充它null。请注意,可能删除场景中的GameObject(而不是使用findNeighours刷新)可能会使其保留null引用。

检查您是否已定义goal

注意:通过邻居你的意思是邻居?