- Home /
Vector3.Distance giving me NullReferenceException every time
Hello, I'm trying to use the Vector3.Distance() function to find the distance between the 2 position.x variables.
In one script, which belongs to the first gameObject im trying to find the distance for has the code:
var distance = Vector3(thisObject.transform.position, OtherObject.staticTransform.staticPosition);
whereas for the "thisObject" i have the transform as a private variable and find it in a Start() function using GetComponent(Transform);
then in another script for another object, i have a transform variable for it set to static that im using for "OtherObject" in the code
But no matter what I do, it keeps throwing me a NullReferenceException pointing to that line of code. I'm almost positive it has something to do with the finding of the other object's position, but I've tried countless things and can't seem to figure it out.
Any help would be great! Thanks!!
We don't have any idea what staticTransform.staticPosition is. That's not in the Unity API. In addition, you're not using unity conventions; "OtherObject" should be "otherObject". "OtherObject" implies a static variable.
Answer by Jaap Kreijkamp · Mar 21, 2010 at 11:55 PM
There are basically three possible null pointers in you code, try to find which is the one by adding some simple debug:
Debug.Log("thisObject = " + thisObject); Debug.Log("OtherObject = " + OtherObject); Debug.Log("OtherObject.staticTransform = " + OtherObject.staticTransform);
var distance = Vector3(thisObject.transform.position, OtherObject.staticTransform.staticPosition);