What is wrong with this script? I have a new project with a Main Camera, then I attached the default Camera-Control → “Smooth Follow” script to it.
I then made a cube and attached this script to it so I can get the distance from the SmoothFollow script:
function Update () {
var other1 : GameObject = GameObject.Find("MainCamera");
var other : SmoothFollow = other1.GetComponent(SmoothFollow);
Debug.Log("What is the distance?"+other.distance);
}
And I keep getting the “NullReferenceException”. Am I calling the wrong name for the SmoothFollow component? Are double quotes needed? Which name should I use?
I’d always use no quotes with GetComponent because if you write the name wrong you’ll get a compile-time error instead of a run-time one, which is harder to debug.
Look at the line you get the NullReferenceException on and check all vars if they are null. Presumably, either Find() or GameObject() return a null object.
Sorry, I know where the error is, I just don’t know how to fix it. The error is in the line:
var other : SmoothFollow = other1.GetComponent(SmoothFollow);
It’s a Script component called “Smooth Follow” and is attached to the GameObject “Main Camera”. It’s the default script that comes with Unity in the Camera scripts, nothing has been modified. “distance” is a public variable so all GameObjects should be able to see it.
I cannot believe this is as hard as I’m making it.
[EDIT]
Currently figured it out. In the Hierarchy View my camera was named “Main Camera” and in the Inspector I was looking at the “tag” which is “MainCamera” BUT the Find() function is looking for the name in the Hierarchy View. From this I was able to get this to show a value of a component in the “Main Camera”
var go = GameObject.Find("Main Camera"); Debug.Log("Test:"+go.GetComponent(SmoothFollow).distance);
The main thing to understand is that Unity is not showing you that it didn’t find your object, you will need to test to see if it is NULL.
var go = GameObject.Find("MainCamera");
Because it will not return a error for an GameObject that doesn’t exist UNTIL you try to do something with it (such as look for it’s components). You will need to test if the return is NULL before you try and do anything to it.