המשחק הסתיים
שיעור 12 מתוך 16 בקורס משחק Unity: שובר לבנים של Coddy.
אובדן החיים האחרון מסיים את המשחק. הכדור יוצא מהמשחק, חלונית סיום המשחק מכסה את המסך, וכפתור המשחק שוב שלה מתחיל משחק חדש. כעת הסצנה כוללת את החלונית, מוסתרת, בתוך בד הציור של ה-HUD, ורשימת On Click של הכפתור ב-Inspector כבר קוראת ל-GameManager.PlayAgain. רשימת On Click מציעה רק מתודות public, לכן המתודה שתבחר לכפתור חייבת להיות ציבורית.
הדרך הפשוטה ביותר להתחיל משחק חדש היא לטעון מחדש את הסצנה. כל אובייקט נוצר מחדש מהסצנה: GameManager חדש עם ניקוד 0 ו-3 חיים, קיר חדש, והכדור חוזר אל המחבט. הסצנה שפועלת היא SceneManager.GetActiveScene(), וה-buildIndex שלה הוא המספר שלה בבנייה:
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);הסתרת הכדור באמצעות SetActive(false) עוצרת את Update() שלו, כך ש-Space כבר לא יכול לשגר אותו, וגם מוציאה אותו מהפיזיקה. הבדיקה מתבצעת אחרי lives--, כך שהמשחק מסתיים כשהחיים מגיעים ל-0: הכדור השלישי שאובד, כאשר מספר החיים מתחיל ב-3.
אתגר
בינוני- הוסף את
using UnityEngine.SceneManagement;ואתpublic GameObject gameOverPanelל־GameManager. הסצנה מקשרת אל GameOverPanel המוסתר. - ב־
BallLost, כשנגמרים החיים האחרונים, הצג את הפאנל והסתר את הכדור שאבד באמצעותSetActive(false), במקום להחזיר אותו אל המחבט. - כתוב את
public void PlayAgain(), שטוענת מחדש את הסצנה הפעילה. הכפתור Play Again שבפאנל כבר קורא לה.
לחץ על הפעל, איבד את שלושת הכדורים, לחץ על שחק שוב ואז על בדיקה.
נסו בעצמכם
using UnityEngine;
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;
int score;
int level;
int bricksLeft;
void Awake()
{
Instance = this;
}
void Start()
{
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 (bricksLeft == 0)
{
ball.ResetToPaddle();
BuildLevel((level + 1) % levels.Length);
}
}
public void BallLost(Ball lost)
{
lives--;
ShowHud();
lost.ResetToPaddle();
}
void ShowHud()
{
scoreText.text = "Score: " + score;
livesText.text = "Lives: " + lives;
}
}
השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.