Menu
CoddyTech

ניקוד שיא

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

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

void GameOver()
{
    int best = PlayerPrefs.GetInt("PinballBest", 0);
    if (score > best)
    {
        PlayerPrefs.SetInt("PinballBest", score);
        PlayerPrefs.Save();
        Debug.Log("New high score: " + score);
    }
}

ההשוואה היא שהופכת את התוצאה לשיא. בלעדיה, משחק עם תוצאה של 300 אחרי שיא של 5000 היה שומר את 300, והשיא היה אובד. השווה לשיא השמור, ולא למשהו שמתחיל ב־0 בכל משחק: שדה שלא נטען אליו שום ערך הוא 0 אחרי כל הפעלה מחדש, ולכן כל תוצאה גבוהה ממנו. score > best משאיר את השיא הישן במקרה של תיקו, ואילו score >= best היה מחשיב תיקו לשיא חדש.

כדי להציג את השיא במהלך המשחק, טען אותו לשדה בתוך Start() והצג את השדה הזה. כשמשחק משיג שיא חדש, עדכן יחד את השדה, את PlayerPrefs ואת הטקסט, כדי שהמסך והערך השמור לעולם לא יציגו מידע סותר.

challenge icon

אתגר

בינוני

שמור על ניקוד שיא תחת המפתח BestPoints.

  1. בתוך Start(), מעל ShowBest();, כתוב best = PlayerPrefs.GetInt("BestPoints", 0);.
  2. בתוך EndRound(), בתוך if (points > best): הגדר best = points;, שמור אותו באמצעות PlayerPrefs.SetInt ו-PlayerPrefs.Save(), ואז קרא ל-ShowBest(); ול-newBestText.SetActive(true);.

לחץ על "שחק" ונפח בלון (החזק את Space ושחרר), ואז לחץ על עצירה ועל "שחק": ניקוד השיא נשמר. לאחר מכן לחץ על "בדיקה".

נסו בעצמכם

using UnityEngine;
using TMPro;

public class BalloonPump : MonoBehaviour
{
    public TMP_Text pointsText;
    public TMP_Text bestText;
    public GameObject newBestText;
    public float pumpRate = 20f;

    private float air;
    private int points;
    private int best;
    private bool roundOver;

    void Start()
    {
        ShowBest();
    }

    void Update()
    {
        if (roundOver) return;

        if (Input.GetKey(KeyCode.Space))
        {
            air += pumpRate * Time.deltaTime;
            transform.localScale = Vector3.one * (1f + air / 50f);
            pointsText.text = "Points: " + Mathf.FloorToInt(air);
            if (air > 100f)
            {
                points = 0;
                pointsText.text = "Pop! Points: 0";
                GetComponent<Renderer>().enabled = false;
                roundOver = true;
                EndRound();
            }
        }
        else if (Input.GetKeyUp(KeyCode.Space))
        {
            points = Mathf.FloorToInt(air);
            pointsText.text = "Points: " + points;
            roundOver = true;
            EndRound();
        }
    }

    void EndRound()
    {
        // שמרו כאן שיא חדש
    }

    void ShowBest()
    {
        bestText.text = "Best: " + best;
    }
}

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

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