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