- Home /
Problem with calculating distance
So I'm trying to make a script that checks that a tagged object is still near it after three seconds. If it's still less than a certain distance away, the script will load the "completed" state for the level through a separate script called DataCenter.
For whatever reason, though, once I added the distance calculation it started giving me null reference errors. Here's the code:
var bulletObject : GameObject;
var endStar : GameObject;
function Update ()
{
}
function OnTriggerEnter(hit : Collider)
{
if(hit.tag == "Player")
{
yield WaitForSeconds (3);
var distance = Vector3.Distance(bulletObject.position, endStar.position);
if (distance > 3.0f) {
DataCenter.allDestroyed=true;
}
}
}
The error is on line 14
Anyone have any idea why this might be happening? I'm still new to the coding side of game development.
Has the bullet been destroyed by 3 seconds after? Has the endStar?
I copy/pasted that allDestroyed call from another script. The bullet doesn't actually need to be destroyed and it works just fine if I remove the distance calculation.
One of those two things in the distance calculate or both have been destroyed or were never set by the time the code gets to them.
Add:
Debug.Log(bulletObject != null ? "Has Bullet" : "Bullet does not exist");
Debug.Log(endStar != null ? "Has End Star" : "End star does not exist");
Before the distance calculation.
Answer by dchen05 · Jun 19, 2013 at 12:54 AM
if bulletObject and endStar are gameobjects as stated at the top of your code, you need to use transform.
Line 14 should be
var distance = Vector3.Distance(bulletObject.transform.position, endStar.transform.position);
If thats not it, try Debug.Log on both of those objects on line 13 to make sure they are there.