Distance Script

I’m writing a script that will allow the player to walk up to an NPC and press a button to talk. Obviously, the character needs to be a certain distance to talk. So I wrote a basic script to test it out:

var char : Transform;
var can_talk = 0;

function Update () {
    if (Vector3.Distance(char.position, transform.position) < 20 ) {
        can_talk = 1;
        print ("You can talk to this character!")
    }
}

I always start the camera on the other side of the island were my game is. I’m sure that the distance is greater than 20, but it still prints “You can talk to this character!”. Any thoughts?[/code]

EDIT: Nevermind, I fixed it.

could you please post the corrected script?

You could also just use a trigger.

I have a sign script that is similar.

The sign has a trigger on it (in addition to a non-trigger collider).

Use OnTriggerEnter to set a flag, and OnTriggerExit to clear it.

when the user presses the button, check the flag, and if it’s set, then let the conversation work. This method doesn’t require an update().