I have a “GameLogic” GameObject wich has some information about certain GameObject’s I’d like my actor (Actor_1) to use for pathfinding.
On the GameLogic GameObject I have a script called ‘PathfindingScript’ for general usage.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PathfindingScript : MonoBehaviour
{
public GameObject nodeA;
public GameObject nodeB;
// Lots of other stuff in here. //
}
I can see ‘nodeA’ and ‘node B’ in the inspector. And it’s working fine.
By pressing a key I spawn my “Actor_1” GameObject into the scene and the console says “Actor 1 is awake”. So that is working! Actor_1 has the following script.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PathCopyScript1 : MonoBehaviour
{
PathfindingScript pathfindingScript;
private GameObject gameLogic;
public GameObject nodeA;
public GameObject nodeB;
private int layer_mask;
//Lots of other stuff. //
void Awake()
{
print("Actor1 is Awake!");
layer_mask = LayerMask.GetMask("Pf_Nodes_Layer");
gameLogic = GameObject.FindGameObjectWithTag("GameLogic");
pathfindingScript = GetComponent<PathfindingScript>();
}
void Update()
{
// Lots of stuff //
if (Input.GetKeyDown("2"))
{
nodeA = pathfindingScript.nodeA;
nodeB = pathfindingScript.nodeB;
}
// Lots of other stuff. //
}
This thing goes wrong when I hit ‘2’.
Console: Object referene is not set to an instance of an object.
This is a generic error, it’s essential to know where exactly the error occurs. Therefore always post the full error including stack trace and line numbers.
This occurs when you assume a variable contains an object reference but it actually doesn’t (the variable is null). The first thing you need to figure out is which variable is null. The exact location of the error is crucial for this. Also, as Jeff pointed out, use Debug.Log to print out the variables to make sure they actually contain what you expect.
Well, and again it’s human error.
Did more debugging and pathfindingScript was ‘Null’.
So I changed pathfindingScript = GetComponent<PathfindingScript>();
into pathfindingScript = gameLogic.GetComponent<PathfindingScript>();
and voila!
I was expecting the code to be fine, because the well trained eye of the community did not spot this. Ah well, problem solved and learned something today.