Menu
CoddyTech

Limpiar

Parte de la sección Fundamentos de scripting en Unity del Journey de Unity de Coddy. Lección 62 de 67.

challenge icon

Desafío

Intermedio

Los bloques nunca desaparecen: después de un minuto de juego, 60 de ellos están cayendo debajo del suelo, y el script sigue moviéndolos a todos. Conserva todo lo de los pasos anteriores y cambia el bucle que mueve los bloques:

  • Un bloque cuyo valor de y está por debajo de -1 está debajo del suelo. Destrúyelo y elimínalo de blocks para que el bucle deje de moverlo.

Presiona Play y después Check.

Pruébalo tú mismo

using System.Collections.Generic;
using UnityEngine;

public class Runner : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private float laneEdge = 4f;
    [SerializeField] private GameObject blockPrefab;
    [SerializeField] private float spawnEvery = 1f;
    [SerializeField] private float fallSpeed = 5f;

    private List<GameObject> blocks = new List<GameObject>();
    private float timer;

    void Update()
    {
        Vector3 p = transform.position;
        p.x += Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
        p.x = Mathf.Clamp(p.x, -laneEdge, laneEdge);
        transform.position = p;

        timer += Time.deltaTime;
        if (timer >= spawnEvery)
        {
            timer = 0f;
            Vector3 spot = new Vector3(Random.Range(-laneEdge, laneEdge), 10f, 0f);
            blocks.Add(Instantiate(blockPrefab, spot, Quaternion.identity));
        }

        foreach (GameObject block in blocks)
        {
            block.transform.position += Vector3.down * fallSpeed * Time.deltaTime;
        }
    }
}

Todas las lecciones de Fundamentos de scripting en Unity