Menu
CoddyTech

Hazlo tuyo

Lección 19 de 19 del curso Juego en Unity: Rompe ladrillos de Coddy.

La última característica es una puntuación máxima que se conserva entre partidas. PlayerPrefs guarda valores pequeños en el dispositivo del jugador: PlayerPrefs.GetInt(key, 0) lee uno, 0 si aún no se ha guardado nada, y PlayerPrefs.SetInt(key, value) guarda uno. «Jugar de nuevo» vuelve a cargar la escena y el nuevo GameManager vuelve a cargar la puntuación máxima.

Después, puedes ajustar el juego a tu gusto. Cada número que determina cómo se juega es un campo con un valor inicial en el código, y el Inspector del jugador es de solo lectura, así que cámbialos ahí:

  • Ball: speed (9) y minVertical (0.3).
  • Paddle: speed (14), wideFactor (1.6) y wideSeconds (8).
  • GameManager: lives (3) y dropChance (0.15).
challenge icon

Desafío

Difícil

Conserva la mejor puntuación entre partidas y después ajusta el juego.

  1. En GameManager, añade public TMP_Text bestText; y int best;; Start() comienza con best = PlayerPrefs.GetInt("BestScore", 0);
  2. ShowHud() también establece bestText.text = "Best: " + best;
  3. Cuando se pierde la última vida con score > best, establece best, PlayerPrefs.SetInt("BestScore", best); y llama a ShowHud().
  4. Ajusta las velocidades, las vidas y dropChance donde se declaran en el código.

Pulsa «Jugar» y consigue una mejor puntuación: se conserva después de «Jugar de nuevo». Luego, pulsa «Comprobar».

Pruébalo tú mismo

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using TMPro;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    public Brick brickPrefab;
    public Transform wall;
    public string[] levels;
    public float spacingX = 1.75f;
    public float spacingY = 0.75f;
    public float topY = 6f;

    public Ball ball;
    public int lives = 3;
    public TMP_Text scoreText;
    public TMP_Text livesText;
    public GameObject gameOverPanel;
    public GameObject[] powerUps;
    public float dropChance = 0.15f;

    int score;
    int level;
    int bricksLeft;
    List<Ball> balls = new List<Ball>();

    void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        balls.Add(ball);
        BuildLevel(0);
        ShowHud();
    }

    void BuildLevel(int index)
    {
        level = index;
        string[] rows = levels[index].Split('/');
        for (int row = 0; row < rows.Length; row++)
        {
            string line = rows[row];
            float left = -(line.Length - 1) * spacingX / 2f;
            for (int col = 0; col < line.Length; col++)
            {
                char c = line[col];
                if (c == '.') continue;
                Vector3 pos = new Vector3(left + col * spacingX, topY - row * spacingY, 0f);
                Brick brick = Instantiate(brickPrefab, pos, Quaternion.identity, wall);
                brick.SetHits(c - '0');
                bricksLeft++;
            }
        }
    }

    public void BrickBroken(Brick brick)
    {
        score += brick.points;
        bricksLeft--;
        ShowHud();
        if (Random.value < dropChance)
        {
            GameObject prefab = powerUps[Random.Range(0, powerUps.Length)];
            Instantiate(prefab, brick.transform.position, Quaternion.identity);
        }
        if (bricksLeft == 0)
        {
            balls[0].ResetToPaddle();
            BuildLevel((level + 1) % levels.Length);
        }
    }

    public void BallLost(Ball lost)
    {
        if (balls.Count > 1)
        {
            balls.Remove(lost);
            Destroy(lost.gameObject);
            return;
        }
        lives--;
        ShowHud();
        if (lives == 0)
        {
            gameOverPanel.SetActive(true);
            lost.gameObject.SetActive(false);
        }
        else lost.ResetToPaddle();
    }

    public void SplitBall()
    {
        Ball source = balls[0];
        Ball left = Instantiate(source, source.transform.position, Quaternion.identity);
        left.Launch(new Vector3(-0.6f, 1f, 0f));
        balls.Add(left);
        Ball right = Instantiate(source, source.transform.position, Quaternion.identity);
        right.Launch(new Vector3(0.6f, 1f, 0f));
        balls.Add(right);
    }

    public void PlayAgain()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }

    void ShowHud()
    {
        scoreText.text = "Score: " + score;
        livesText.text = "Lives: " + lives;
    }
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Juego en Unity: Rompe ladrillos

Practica por tu cuenta: Playground de Unity