Do an action when I'm moved determined distance

Hello.
I’m making a game and I want to do an action, for example print a text in the console, but only print the text one time, when I’m moved a determined distance. I made this script but does not work:
(I use this script also for show the Walked distance in the screen.)

var WalkedDistance : float = 0;
var lastPosition : Vector3;
var style : GUIStyle;

function Start()
{
lastPosition = transform.position;
}

function Update() {
WalkedDistance += Vector3.Distance(transform.position, lastPosition);

lastPosition = transform.position;

if(WalkedDistance >= 100){   //This does not work
    print("TEXT");
}
}

function OnGUI()
{
    GUILayout.Label("Walked distance = " + WalkedDistance);
}

I hope someone can help me. Kind regards.

The distance walked on any frame will never exactly equal 100.
It will be off by some decimal amount.

Try this:
if(WalkedDistance > 100)

I think in it, but if I use this script, then, the message will print infinite times and I want to print the message only one time. Would you know how to do it? c:
Thanks for reply.

you can create a flag boolean hasGone100
set that to true inside the “if” statement
and test for it too

if(WalkedDistance > 100 && hasGone100 == false)
hasGone100 = true;

1 Like

I’m a bit noob in programming and Unity 3D and… how I create a flag boolean? :face_with_spiral_eyes:

There was no reply box in the message you sent me, not sure why.
So I will answer here.

If this is actually a project, then it sounds like school homework and you should do it yourself.
If you dont know how to declare a boolean, or what one even is, you need to read a book, not ask questions on a forum.
Thats the best advice I can give you.

Ok. Indeed the project isn’t serious, just I’m doing it to learn and have fun xD
I searched how to a create a flag boolean and I wrote this script:

var WalkedDistance : float = 0;
var lastPosition : Vector3;
var style : GUIStyle;
var hasGone100  : boolean = false;

function Start()
{
lastPosition = transform.position;
}
function Update() {
WalkedDistance += Vector3.Distance(transform.position, lastPosition);
lastPosition = transform.position;
if(WalkedDistance > 10 && hasGone100 == false) {
    hasGone100 = true;
    print("TEXT");
}
}
function OnGUI()
{
    GUILayout.Label("Walked distance = " + WalkedDistance);
}

Now works correct :slight_smile: Thank you very much for your help :wink:

You’re welcome.
Congrats on figuring out the last part yourself :slight_smile: