Search code examples
c#unity-game-engine2d-games

How to let objects fall down continually


I have started learning Unity and want to let objects fall down and collect. So far I have just one object and it falls down just one time. How do i place in into a loop and let it fall over and over again?

public class AppleScript : MonoBehaviour
{
    public float fallSpeed = 8.0f;

    void Start()
    {
        transform.Translate(Vector3.down * fallSpeed * Time.deltaTime, Space.World);
    }

    void Update()
    {
        transform.Translate(Vector3.down * fallSpeed * Time.deltaTime, Space.World);
    }
}

Solution

  • If I undestand it correctly, you want an object to fall down then teleport up to its starting position and then fall down again. Let's do that in code!

        public class AppleScript : MonoBehaviour
        {
            public float fallSpeed = 8.0f;
    
            //Variables for starting position and length until reset
            private Vector3 _startingPos;
            public float FallDistance = 5f;
    
            void Start()
            {
                transform.Translate(Vector3.down * fallSpeed * Time.deltaTime, Space.World);
                // Save starting position
                _startingPos = transform.position;
            }
    
            void Update()
            {
                transform.Translate(Vector3.down * fallSpeed * Time.deltaTime, Space.World);
    
                // If the object has fallen longer than 
                // Starting height + FallDistance from its start position
                if (transform.position.y > _startingPos.y + FallDistance) {
                    transform.position = _startingPos;
                }
            }
        }