简体   繁体   中英

I'm Getting this error in Unity3D - NullReferenceException: Object reference not set to an instance of an object

I'm getting an error while developing FPS game in Unity 3D

NullReferenceException: Object reference not set to an instance of an object Node.OnDrawGizmos () (at Assets/Node.cs:14)

It working fine earlier but when I added layer to the nodes then I got this error.

check out with the complete code

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


        }
    }
}

}

I see findNeighours does not feed neighours , so I imagine you want something like:

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

About OnDrawGizmos , potentially path and neighours could be holding null items. You should check if that's the case and see why it's filling with it null s. Note that probably removing a GameObject in the scene (and not refreshing using findNeighours ) could make it hold null references.

Check if you have defined goal .

Note: by neighours you mean neighbors?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM