- Home /
Why won't my character register as near?
#pragma strict
var player : Transform;
var distance = 7;
private var playerCloseEnough = false;
function Start () {
}
function Update () {
if(Vector3.Distance(transform.position, player.position) < distance){
playerCloseEnough = true;
}
else{
playerCloseEnough = false;
}
if (playerCloseEnough == true){
print("It works!");
}
else
{
print("It doesn't work!:(");
}
}
This is attached to a cube that is supposed to detect when the player is near. So far It doesn't register as I always get "It doesn't work!". Any idea's?
Answer by TrickyHandz · Oct 06, 2013 at 02:37 AM
Your script is written fine and it works. I just tried it out in a new project with a cube and a sphere, where the script was on the cube and the sphere assign as the player. As soon as I moved my sphere inside the range it worked as expected.
I would recommend changing your "It doesn't work" code to printing the distance so you can see how far away you actually are. Like this:
print(Vector3.Distance(transform.position, player.position));
When I try that- it looks as if Unity takes the distance from when the game starts and then doesn't update and continue checking the distance. It's very odd. I'm kinda at a loss.
That is rather strange. As I said your code works right out of the box for me. Try it in a new empty scene to see if something else is causing an issue. If it works in a new scene with just two objects the culprit is elsewhere.
Actually I take that back. I started the player in a different spot and it gave me the same number...86.9916. So that's a problem. I'll try an empty scene and hopefully it'll work.
So I did try it and it this point- it still doesn't work for me. This time it gives me a number in the 70's. Really at a loss here. I'm not sure what could be causing the problem. EDIT: So apparently I have to drag the player controller from the hierarchy for it to work. So it's solved then.
Answer by darkhog · Oct 06, 2013 at 03:23 AM
Why so much ifs? First of all, you could simplify first if as
playerCloseEnough = (Vector3.Distance(transform.position, player.position) < distance
But even that's not needed, as you can just do:
if ((Vector3.Distance(transform.position, player.position) < distance){
print("It works!");
}
else
{
print("It doesn't work!:(");
}
}
This way you'll avoid unnecessary ifs which may make your game run faster.