- Home /
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:
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;NullReferenceException: Object reference not set to an instance of an object
function Update () { transform.LookAt(gridCenter); } 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.
Answer by DaveA · Sep 12, 2012 at 12:50 AM
private var grid = target.GetComponent(generateGrid); <-- Line 5
You can't do that outside a function. Declare the variable, but set it in Start()
Awesome, thanks a bunch. Based on your comment, I was able to figure it out. This also gave me an indicator that I needed to study how Unity's scripting works in a bit more detail. So I've been doing that for a few days, and it's amazing how everything starts to fall into place. Thanks again. :)
Your answer
Follow this Question
Related Questions
script GetComponent, nullReference error 1 Answer
Assign collider and linerenderer to list 1 Answer
Script Referencing 2 Answers
Get Component from Instantiated Prefab 1 Answer
NullReferenceException....Again(sorry) 0 Answers