ניקוד שיא
חלק מהיחידה בניית משחקים אמיתיים במסלול ה-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 ואת הטקסט, כדי שהמסך והערך השמור לעולם לא יציגו מידע סותר.
אתגר
בינונישמור על ניקוד גבוה תחת המפתח BestPoints.
- ב־
Start(), מעלShowBest();, כתובbest = PlayerPrefs.GetInt("BestPoints", 0);. - ב־
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;
}
}
כל השיעורים ביחידה בניית משחקים אמיתיים
10פרויקט: משחק פלטפורמה תלת־ממדי
המסלולפלטפורמות נעותתרגלו בעצמכם: Unity אונליין