Menu
CoddyTech

أفضل جولة

جزء من قسم إنشاء ألعاب حقيقية في رحلة Unity على Coddy. الدرس 33 من 60.

الخطوة الأخيرة في لعبة العَدّاء اللانهائي: تُحفَظ أفضل محاولة في 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);.

اضغط على «العب»، وسجّل أفضل نتيجة، ثم تجاوزها: ستظهر رسالة «أفضل نتيجة جديدة!». ثم اضغط على «تحقق».

جرّب بنفسك

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اختبر نفسك

يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.

جميع دروس إنشاء ألعاب حقيقية

تدرّب بنفسك: Playground لـ Unity