1
剛剛學習Unity/C#並且在保存PlayerPrefs時遇到了一些大問題。我們需要使用它們,儘管它們從未被解釋過,並且我試圖通過在線來源進行工作的所有代碼迄今爲止都失敗了。請記住,我仍在學習,所有反饋將不勝感激!我試圖保存水平完成的時間(在所有事情都在舞臺上死亡之後),並使用playerpref設置函數保持單獨的高分。這裏是我到目前爲止的代碼:Unity C#PlayerPrefs /無法讓它工作
using UnityEngine;
using System.Collections;
public class playerScript : MonoBehaviour {
public float currentHealth = 100; // Player Hp
private float restartDelay = 5f; // Time to wait before restarting the level
public float restartTimer; // Timer to count up to restarting the level
public float thrust = 100f;
public Rigidbody rb;
private string textFieldString; // Declaring a text field into a string
public bool isFinished; // Checking if game has finished or not
public static float bestTime = PlayerPrefs.GetFloat ("HighScore", 0);
float gameTime;
// Use this for initialization
void Start() {
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update() {
gameTime += Time.deltaTime;
if(currentHealth <= 0) {
currentHealth = 0;
restartTimer += Time.deltaTime;
// .. if it reaches the restart delay...
if(restartTimer >= restartDelay)
{
// .. then reload the currently loaded level.
Application.LoadLevel(Application.loadedLevel);
}
}
//When all enemies are cured, calls this code
if(GameObject.FindGameObjectsWithTag("Enemy").Length==0) {
isFinished = true;
//Application.LoadLevel(Application.loadedLevel);
}
if (isFinished == true) {
bool isNewHighscore = false;
if (gameTime < bestTime)
{
PlayerPrefs.SetFloat ("HighScore", gameTime);
Debug.Log ("HighScoreSet");
}
bestTime = PlayerPrefs.GetFloat("Best Time");
}
}
void OnCollisionEnter(Collision collision) {
// Reduce health
if (collision.gameObject.tag == "Enemy") {
currentHealth -= collision.gameObject.GetComponent<ZombieBotAi>().zombieDamage;
rb.AddForce (transform.forward * thrust);
}
}
//Event for running into healing bottles
void OnTriggerEnter(Collider other){
switch(other.gameObject.tag)
{
case "Heal":
ChangeHP(25);
break;
}
//Destroys healing bottle after collision
Destroy (other.gameObject);
}
//Displays Current HP on GUI
void OnGUI(){
textFieldString = GUI.TextField (new Rect (35, 500, 140, 30),"HP\t: " + currentHealth.ToString());
textFieldString = GUI.TextField (new Rect (800, 35, 140, 30),"Best Time\t: " + PlayerPrefs.GetFloat ("HighScore"));
if(GameObject.FindGameObjectsWithTag("Enemy").Length==0) {
textFieldString = GUI.TextField (new Rect (600, 300, 230, 30), "You have won the game in " + gameTime + " seconds!");
}
if (currentHealth <= 0) {
textFieldString = GUI.TextField (new Rect (600, 300, 230, 30), "You have been infected! Game Over !!");
}
}
//HP cant go above 100
void ChangeHP(float Change){
currentHealth += Change;
if (currentHealth > 100) {
currentHealth=100;
}
}
}
你沒有解釋你的問題。你有什麼問題?什麼不工作,你是否得到錯誤? – Programmer
我沒有讀過你的代碼,因爲你沒有解釋問題是什麼。但是在爲PlayerPrefs設置一個值後,請記得調用PlayerPrefs.Save(),否則將不會保存。 – JeanLuc
問題是我有0線索需要什麼來獲得playerprefs保存,然後正確調用它來顯示高分,當我需要它。 –