• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
Question by Elektrobomb · Oct 03, 2016 at 10:17 PM · scripting problemnullreferenceexeption

NullReferenceException: Object reference not set to an instance of an object

I seem to have an issue that several others have had but each situation seems to be somewhat unique in it's solving and thus, as of yet I have been unable to ascertain the issue. Basically, when I run my P2P_guide.cs script, it kicks out this error in the debug console:

NullReferenceException: Object reference not set to an instance of an object Grid_Manager.NodeFromWorldPoint (Vector3 worldPosition) (at Assets/Pathfinding_Resources/Grid_Manager.cs:65) Pathfinding.FindPath (Vector3 startPos, Vector3 targetPos) (at Assets/Pathfinding_Resources/Pathfinding.cs:21) P2P_guide.amble () (at Assets/Pathfinding_Resources/P2P_guide.cs:25) P2P_guide.Start () (at Assets/Pathfinding_Resources/P2P_guide.cs:20)

As you can see, this is quite a complex error and seeing as I have not been programming in c# for too long and thus am relatively inexperienced I have spent ages trying to find the problem but no luck and so I was wondering if a fresh set of eyes could shed some light on the situation? Here are the scripts I am running:

This one is attached to a player object:

P2P_guide

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class P2P_guide : MonoBehaviour {
 
     GameObject pathobj;
     Grid_Manager grid;
     public List<Node_Manager> path;
     Pathfinding pathfinder;
     public Transform Destination;
     public List<Vector3> pathcoords;
     public Transform Player;
 
 
     void Start() {
         pathobj = GameObject.Find ("A*");
         grid = pathobj.GetComponent<Grid_Manager> ();
         pathfinder = pathobj.GetComponent<Pathfinding> ();
         amble ();
 
     }
     void amble() {
         
         pathfinder.FindPath (Player.position, Destination.position);
         path = grid.path;
         pathcoords = new List<Vector3>();
         foreach (Node_Manager node in path) {
             pathcoords.Add (grid.WorldPointFromNode (node));
         }
 
         transform.LookAt (pathcoords [1]);
     
     }
 }

and then these three are attached to a game object called "A*" in the middle of the map:

Pathfinding

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Pathfinding : MonoBehaviour {
 
     public Transform seeker, target;
 
     Grid_Manager grid;
 
     void Awake() {
         grid = GetComponent<Grid_Manager> ();
     }
         
 
 /*    void Update() {
         FindPath (seeker.position, target.position);
     }
 */
     public void FindPath(Vector3 startPos, Vector3 targetPos) {
         Node_Manager startNode = grid.NodeFromWorldPoint (startPos);
         Node_Manager targetNode = grid.NodeFromWorldPoint (targetPos);
 
         List<Node_Manager> openSet = new List<Node_Manager> ();
         HashSet<Node_Manager> closedSet = new HashSet<Node_Manager> ();
         openSet.Add (startNode);
 
         while (openSet.Count > 0) {
             Node_Manager currentNode = openSet [0];
             for (int i = 1; i < openSet.Count; i ++) {
 
                 if (openSet [i].fCost < currentNode.fCost || openSet[i].fCost == currentNode.fCost && openSet[i].hCost < currentNode.hCost) {
                     currentNode = openSet [i];
                 }
 
             }
 
             openSet.Remove (currentNode);
             closedSet.Add (currentNode);
 
             if (currentNode == targetNode) {
                 RetracePath (startNode, targetNode);
                 return;
             }
 
             foreach (Node_Manager neighbour in grid.GetNeighbours(currentNode)) {
                 if (!neighbour.walkable || closedSet.Contains (neighbour)) {
                     continue;
                 }
 
                 int newMovementCostToNeighbour = currentNode.gCost + GetDistance (currentNode, neighbour);
                 if (newMovementCostToNeighbour < neighbour.gCost || !openSet.Contains (neighbour)) {
                     neighbour.gCost = newMovementCostToNeighbour;
                     neighbour.hCost = GetDistance (neighbour, targetNode);
                     neighbour.parent = currentNode;
 
                     if (!openSet.Contains (neighbour)) {
                         openSet.Add (neighbour);
                     }
                 }
 
             }
         }
     }
 
     void RetracePath (Node_Manager startNode, Node_Manager endNode) {
         List<Node_Manager> path = new List<Node_Manager> ();
         Node_Manager currentNode = endNode;
 
         while (currentNode != startNode) {
             path.Add (currentNode);
             currentNode = currentNode.parent;
         }
         path.Reverse ();
 
 
         grid.path = path;
 
 
     }
 
     int GetDistance(Node_Manager nodeA, Node_Manager nodeB) {
         int distX = Mathf.Abs (nodeA.gridX - nodeB.gridX);
         int distY = Mathf.Abs (nodeA.gridY - nodeB.gridY);
 
         if (distX > distY) {
             return 14 * distY + 10 * (distX - distY);
         } 
 
         else {
             return 14 * distX + 10 * (distY - distX);
         }
     }
 }
 
 

Grid_Manager

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Grid_Manager : MonoBehaviour {
 
     public Transform player;
     public LayerMask unwalkableMask;
     public Vector2 gridWorldSize;
     public float nodeRadius;
     Node_Manager[,] grid;
     public Vector3 worldBottomLeft;
 
     float nodeDiameter;
     int gridSizeX, gridSizeY;
 
     void Start() {
         nodeDiameter = nodeRadius * 2;
         gridSizeX = Mathf.RoundToInt (gridWorldSize.x / nodeDiameter);
         gridSizeY = Mathf.RoundToInt (gridWorldSize.y / nodeDiameter);
         CreateGrid ();
     }
 
     void CreateGrid() {
         grid = new Node_Manager[gridSizeX,gridSizeY];
         worldBottomLeft = transform.position - Vector3.right * gridWorldSize.x/2 - Vector3.forward * gridWorldSize.y/2;
 
         for (int x = 0; x < gridSizeX; x ++) {
             for (int y = 0; y < gridSizeY; y ++) {
                 Vector3 worldPoint = worldBottomLeft + Vector3.right * (x * nodeDiameter + nodeRadius) + Vector3.forward * (y * nodeDiameter + nodeRadius);
                 bool walkable = !(Physics.CheckSphere(worldPoint,nodeRadius,unwalkableMask));
                 grid[x,y] = new Node_Manager(walkable,worldPoint,x,y);
             }
         }
     }
 
     public List<Node_Manager> GetNeighbours(Node_Manager node) {
         List<Node_Manager> neighbours = new List<Node_Manager> ();
 
         for (int x = -1; x <= 1; x++) {
             for (int y = -1; y <= 1; y++) {
                 if (x == 0 && y == 0) {
                     continue;
                 }
                 int checkX = node.gridX + x;
                 int checkY = node.gridY + y;
 
                 if (checkX >= 0 && checkX < gridSizeX && checkY >= 0 && checkY < gridSizeY) {
                     neighbours.Add (grid [checkX, checkY]);
                 }
             }
         }
 
         return neighbours;
     }
 
     public Node_Manager NodeFromWorldPoint(Vector3 worldPosition) {
         float percentX = (worldPosition.x + gridWorldSize.x / 2) / gridWorldSize.x;
         float percentY = (worldPosition.z + gridWorldSize.y / 2) / gridWorldSize.y;
         percentX = Mathf.Clamp01 (percentX);
         percentY = Mathf.Clamp01 (percentY);
 
         int x = Mathf.RoundToInt((gridSizeX - 1) * percentX);
         int y = Mathf.RoundToInt((gridSizeY - 1) * percentY);
         return grid [x, y];
     }
 
 
     public Vector3 WorldPointFromNode(Node_Manager node) {
         Node_Manager Node = node;
         int x = Node.gridX;
         int y = Node.gridY;
         int roundrad = Mathf.RoundToInt (nodeRadius);
         int posx = Mathf.RoundToInt (worldBottomLeft.x) + (x*roundrad);
         int posy = Mathf.RoundToInt (worldBottomLeft.y) + (y*roundrad);
         Vector3 pos = new Vector3(posx,0,posy);
         return pos;
     }
 
     public List<Node_Manager> path;
 
     void OnDrawGizmos() {
         Gizmos.DrawWireCube (transform.position, new Vector3 (gridWorldSize.x, 1, gridWorldSize.y));
     
         if (grid != null) {
             Node_Manager playerNode = NodeFromWorldPoint (player.position);
             foreach (Node_Manager n in grid) {
                 
                 Gizmos.color = (n.walkable) ? Color.white : Color.red;
                 if (playerNode == n) {
                     Gizmos.color = Color.blue;
                 }
                 if (path != null)
                 if (path.Contains (n))
                         Gizmos.color = Color.black;
                 Gizmos.DrawCube (n.worldPosition, Vector3.one * (nodeDiameter - .1f));
             }
         }
     }
 }
 

Node_Manager

 using UnityEngine;
 using System.Collections;
 
 public class Node_Manager {
 
     public bool walkable;
     public Vector3 worldPosition;
     public int gridX;
     public int gridY;
 
     public int gCost;
     public int hCost;
     public Node_Manager parent;
 
     public Node_Manager(bool _walkable, Vector3 _worldPos, int _gridX, int _gridY) {
         walkable = _walkable;
         worldPosition = _worldPos;
         gridX = _gridX;
         gridY = _gridY;
     }
 
     public int fCost {
         get {
             return gCost + hCost;
         }
     }
 }
 

Anyway, thanks in advance and I hope to hear from someone soon!

:)

Comment

People who like this

0 Show 0
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
Best Answer

Answer by flashframe · Oct 03, 2016 at 10:22 PM

The error is saying that "grid" doesn't exist yet.

This might be a problem with script execution order.

You are calling CreateGrid() in the Start method of your GridManager class, but it's possible that the NodeFromWorldPoint method is getting called first, since it is called from the Start method of P2P_Guide.

Try changing this

 void Start() {
          nodeDiameter = nodeRadius * 2;
          gridSizeX = Mathf.RoundToInt (gridWorldSize.x / nodeDiameter);
          gridSizeY = Mathf.RoundToInt (gridWorldSize.y / nodeDiameter);
          CreateGrid ();
      }

to this:

 void Awake() {
          nodeDiameter = nodeRadius * 2;
          gridSizeX = Mathf.RoundToInt (gridWorldSize.x / nodeDiameter);
          gridSizeY = Mathf.RoundToInt (gridWorldSize.y / nodeDiameter);
          CreateGrid ();
      }


Otherwise, you can control the order that Unity runs scripts using Script Execution Order settings: https://docs.unity3d.com/Manual/class-ScriptExecution.html

Comment

People who like this

0 Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Elektrobomb · Oct 03, 2016 at 10:44 PM 0
Share

oh my god, that you so much. I would have never though to check the execution order. That worked perfectly (apart from a couple of unrelated problems in my scripting). Brill, thanks

avatar image flashframe Elektrobomb · Oct 03, 2016 at 10:46 PM 0
Share

You're welcome, glad you got it working :)

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Properly Inherit Classes 1 Answer

What is the new SceneManagement equivalent for Application.Quit? 1 Answer

How to add wait for second for a Editor Script? 0 Answers

Fix for Enemy AI script 0 Answers

how do i get a boolean to switch to true only after i've pressed a key three times? 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges