Menu
CoddyTech

הריצה הטובה ביותר

חלק מהיחידה בניית משחקים אמיתיים במסלול ה-Unity של Coddy. שיעור 33 מתוך 60.

השלב האחרון ב־Endless Runner: הריצה הטובה ביותר נשמרת ב־PlayerPrefs, כמו הניקוד הגבוה ביותר, כך שהיא נשמרת גם לאחר הרצה נוספת ויציאה מהמשחק.

challenge icon

אתגר

בינוני

שמור את הריצה הטובה ביותר תחת המפתח BestRun.

  1. הוסף private int best;. בתוך Start(), טען אותו באמצעות PlayerPrefs.GetInt("BestRun", 0) והצג את "Best: " + best + " m" בתוך bestText.
  2. בסוף GameOver(), כאשר Mathf.FloorToInt(distance) גדול מ־best, שמור אותו, הצג אותו וקרא ל־newBestText.SetActive(true);.

לחץ על "שחק", קבע שיא ואז שפר אותו: תופיע ההודעה New best! לאחר מכן לחץ על "בדיקה".

נסו בעצמכם

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;

public enum GameState { Playing, GameOver }

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    public float speed = 10f;
    public float speedUp = 0.5f;
    public float maxSpeed = 20f;
    public TMP_Text distanceText;
    public GameObject gameOverPanel;
    public Button restartButton;
    public GameState state = GameState.Playing;
    public TMP_Text bestText;
    public GameObject newBestText;
    private float distance;

    void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        restartButton.onClick.AddListener(Restart);
    }

    void Update()
    {
        if (state != GameState.Playing) return;

        speed = Mathf.Min(speed + speedUp * Time.deltaTime, maxSpeed);
        distance += speed * Time.deltaTime;
        distanceText.text = "Distance: " + Mathf.FloorToInt(distance) + " m";
    }

    public void GameOver()
    {
        state = GameState.GameOver;
        speed = 0f;
        gameOverPanel.SetActive(true);
    }

    void Restart()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה בניית משחקים אמיתיים

תרגלו בעצמכם: Unity אונליין