"Object reference not set to instance of object" when using GameObject.FindObjectWithTag?

Not entirely sure what I’ve done wrong here. I’m following a tutorial on how to generate voxel landscapes and I’ve been modifying it here and there so that I can alter settings on the fly whilst in-game. So far so good, until I try to implement chunk loading/unloading.

The code works and I’ve been able to make it work - though I have no idea how. However, I wanted to move the script onto a different GameObject so that I could keep things tidy and organised for myself.

Here is my code:

void Update () {
		if (Time.time >= Timer) {
			LoadChunks(GameObject.FindGameObjectWithTag("Player").transform.position,RenderDistA,RenderDistB);
			Timer += UpdateInterval;
		}
	}

Where Timer and UpdateInterval aren’t what’s broken, the “LoadChunks” part is.
“LoadChunks” is a function in this script that loads chunks based on a Vector3 for the player position, a distance to load (I set up a static variable called RenderDistA) and a distance to unload (I did the same and called it RenderDistB).

It doesn’t look like it shouldn’t work, to me. But when I get in-game the chunks don’t load/unload around the player and I’m getting the “Object reference not set to instance of object” constantly.

Any ideas?

You probably didn’t set the “Player” tag on your player.

GameObject.FindGameObjectWithTag(“Player”) returns null (because you don’t have any GameObject with this tag in your scene) and thus, you’re trying to get the transform member of null, that’s why you get the Null reference exception.
Since an exception is raised, your code breaks and the chunks are never spawned.

Hope this helps :wink: