# How to move a game object up and down in a loop

I am trying to make “apple” move up and down forever with a script. Unfortunately i am struggling as the apple stop as once y reaches 3, Instead of going down, it just stops. I am using unity 2019.3.15f. Heres the code:

``````using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Move : MonoBehaviour
{
public GameObject apple;
public float y;
public float speed;

public void Update()
{
if (y > 3)
{
y = y - speed;
}
if (y < 3)
{
y = y + speed;
}
apple.transform.position = new Vector3(0, y, 0);
}
}
``````

public class Move : MonoBehaviour
{
public GameObject apple;
public float speed;

``````     public void Update()
{
float y = Mathf.PingPong(Time.time * speed, 1) * 6 - 3;
apple.transform.position = new Vector3(0, y, 0);
}
}
``````

Hi,

first of all: In your Update() Loop multiply by Time.delteTime. This way the apple is moving at a constant speed independent of your framerate.

Then I imagine your speed is something like 1 (or 0.1, whatever).

In this case you will have a time when your position will be EQUAL to 3. None of your ifcases will run in this case.

``````public void Update()
{
if (y >= 3)
{
y = y - speed * Time.deltaTime;
}
if (y < 3)
{
y = y + speed * Time.deltaTime;
}
apple.transform.position = new Vector3(0, y, 0);
}
``````

Care: Only one of your if cases should check for equal

Greets

check this out !

``````public int loopHeight = 10;
public bool checkAtMax = false;

void Update()
{
if (checkAtMax)
{
for (int x = 0; x < loopHeight; ++x)
{
apple.transform.position -= new Vector3(0, y, 0);
if (x == loopHeight - 1)
checkAtMax = false;
}
}
else
{
for (int x = 0; x < loopHeight; ++x)
{
apple.transform.position += new Vector3(0, y, 0);
if (x == loopHeight - 1)
checkAtMax = true;
}
}
}
``````

[SerializeField] [Range(0,1)] float speed = 1f;
[SerializeField] [Range(0,100)] float range = 1f;
void Update()
{
loop();
}

``````     void loop()
{
float yPos = Mathf.PingPong(Time.time * speed, 1) * range;
transform.position = new Vector3(transform.position.x, yPos, transform.position.z);
}
}
``````