How do I loop an object from A to B and start again at A

Hi guys, this is my 1st post here and I’m wondering how to make an object (a day & night sky) loop as it goes from A to B and start again at A. It’s a sky image that will loop over and over to simulate the day and night cycle.

When I run the code, the sky just keeps on moving in the y axis. Any suggestions is appreciated :slight_smile:

// erge

using UnityEngine;
using System.Collections;

public class dayNightCycle : MonoBehaviour {

	public float speed = -1f;
	private float startPos = -7.1f;
	private float endPos = 170f;
	private float currentPos;
	
	void Update () {
		currentPos = transform.position.y;
		transform.Translate(0, 0, speed * Time.deltaTime);
		if(currentPos == endPos){
			SetTransformY(startPos);
		}
	}
	
	void SetTransformY(float n){
		transform.position = new Vector3(transform.position.x, n, transform.position.z);
	}
}

You have one problems and one potential problem here. The first is that you are doing this comparison:

if(currentPos == endPos){

Seldom will currentPos land exactly on ‘endPos.’ Usually it will skip over the value, being less than endPos one frame, and more than endPos the next frame. Change the check to:

   if(currentPos >= endPos){

The second potential problem is that you are checking the the ‘Y’ position, but your Translate() code moves your object in the local ‘Z’ direction. So your forward of your object needs to be at least partly facing in the up direction.