time question

hi,

i am very new to scripting.

i am trying to understand how to trigger events when specific amounts of game seconds have passed, like how to make a sound play at exactly 20 seconds.

please can someone explain why my script doesnt work:

in this example i want to make a cube change position when one second has passed. i am confused why it doesn’t recognise the = sign, but if i change it to greater than or less than it does work.

function Update () {

if (Time.timeSinceLevelLoad = 1){
transform.Translate(0, 0, 0.1);
}

}

thank you

First of all, to test for equality, you need to use “double equals” or “==” (ie, “if (Time.timeSinceLevelLoad == 1) …”). The reason the test fails is that in Unity (and computing in general), time is measured in discrete units. So, time may jump from 0.99999 seconds to 1.00001 seconds and it will never be strictly equal to 1. So, checking whether the time is greater than or equal to 1 will ensure that it fires the first frame (and every frame after) the time is more than 1 second. If you want it to just fire once, you can add a boolean that determines whether the translation should happen:

var hasMoved : boolean = false;

function Update () {
    if (Time.timeSinceLevelLoad >= 1  !hasMoved) {
        transform.Translate (0, 0, 0.1);
        hasMoved = true;
    }
}

thank you :smile: that makes sense.