Because you want the object to move relative to time passing rather than distance traveled, Time.deltaTime is very useful. Here’s a more accurate script:
function Update () {
transform.Translate( 0, 0, 2*Time.deltaTime ); // speed; see below
if (transform.localPosition.z >= 10) // at position 10...
transform.rotation = Quaternion.Euler(0,180,0);//face backward
if (transform.localPosition.z <= 0) // at position 0....
transform.rotation = Quaternion.Euler(0,0,0); // face forward
}
What Time.deltaTime does is take the small part of a second that passed since the last frame. If we didn’t modify it, then it would move the object this small amount every frame. Once it all adds up to 1, our object will have moved 1 unit. This also means 1 second will have passed, because the time is where we got our numbers.
So without modifying the number, the object will move 1 unit per second.
Since you want it to move 1 unit per half second, it will move 2 units per second, so we say 2*Time.deltaTime.
Since we’re operating with time now, I changed the script to rotate the object. What’s happening here is that the object moves at a steady 2 units per second (1 per half second) average, and when its z-position hits or passes 100 or 0, the object turns around and goes the other way.
in this example, we use the local z position, meaning “0” is the z position of the object’s parent. If it doesn’t have a parent, then the world origin is “0”
No variables are needed in this example, but you could use some in place of the speed and max distance, to allow changes from the inspector.