NullReferenceException when using GetComponent to access script variables

Hi, I’ve been trying to figure this out for a few days, and I feel utterly defeated coming here to ask. Any help is greatly appreciated.

I’m getting a NullReferenceException on what appears to be straightforward code. I think this stems from a basic misunderstanding of mine about how GetComponent works. Here’s the exact error:

NullReferenceException: Object reference not set to an instance of an object
centerCamera…ctor () (at Assets/Scripts/centerCamera.js:5)

And here’s the code:

in centerCamera.js:

var target : GameObject;
private var grid = target.GetComponent(generateGrid); <-- Line 5
private var gridCenter : Vector3 = grid.gridCenter;

function Update () {

and in generateGrid.js:

var gridCenter : Vector3 = Vector3(originX, originY, zDepth);
// basically Vector3(0, 0, 0.1)

Then in the inspector I have a prefab Empty called gameGrid with the script generateGrid attached to it. The script centerCamera is on the mainCamera object in the hierarchy, with “target” being the gameGrid object.

Why am I getting this error?

Does target.GetComponent(generateGrid) not give me access to the script variables?

Shouldn’t NullReferenceException not occur if I properly set the target in the inspector?

Thanks for your time.

private var grid = target.GetComponent(generateGrid); ← Line 5

You can’t do that outside a function. Declare the variable, but set it in Start()