从得分中设置高分并在unity2D游戏中显示

时间:2017-09-05 14:06:09

标签: c# unity3d unity5 unity2d

我的游戏中得分在某些点上增加!这工作正常但我想要一个保存的高分并且不确定如何实现playerprefs,因为我仍然要掌握团结和c#!到目前为止,我已经在我的画布中放置了一个ui文本元素,这称为高分:0我希望0保持并保存高分!此刻增量的工作分数是在更新方法中。 编辑,只是指出这不是下面发布的链接的重复!两者都在寻找看似相似但不是

的问题的不同答案
public class Player : MonoBehaviour {

public string currentColor;

public float jumpForce = 10f;

public Rigidbody2D circle;
public SpriteRenderer sr;

public Color blue;
public Color yellow;
public Color pink;
public Color purple;

public static int score = 0;
public Text scoreText;


public GameObject obsticle;
public GameObject colorChanger;

void Start () {

    setRandomColor ();
    circle.isKinematic = true;

}

// Update is called once per frame
void Update () {

        if (Input.GetButtonDown ("Jump") || Input.GetMouseButtonDown (0)) 

        {
        circle.isKinematic = false;
            circle.velocity = Vector2.up * jumpForce;
        }

    scoreText.text = score.ToString ();

}

private void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.tag == "Scored") 
    {
        score++;
        Destroy (collision.gameObject);
        Instantiate (obsticle, new Vector2(transform.position.x,transform.position.y + 7f), transform.rotation);
        return;
    }

    if (collision.tag == "ColorChanger") 
    {
        setRandomColor ();
        Destroy (collision.gameObject);
        Instantiate(colorChanger, new Vector2(transform.position.x,transform.position.y + 7f), transform.rotation);
        return;
    }

    if (collision.tag != currentColor) {
        Debug.Log ("You Died");
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        score = 0;
    }

    if (collision.tag == "Floor") 
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}

void setRandomColor()
{
    int rand = Random.Range (0, 4);

    switch (rand) 
    {
    case 0:
        currentColor = "Blue";
        sr.color = blue;
        break;

    case 1:
        currentColor = "Yellow";
        sr.color = yellow;
        break;

    case 2:
        currentColor = "Pink";
        sr.color = pink;
        break;

    case 3:
        currentColor = "Purple";
        sr.color = purple;
        break;
    }
}

}

1 个答案:

答案 0 :(得分:3)

增加分数似乎没有任何问题。如果你想保存高分并让它在游戏中保持不变,我建议你在Assets文件夹中创建一个.txt文件,如果它大于文件中的分数,则将分数写入其中。我没有测试它,因为我在手机上,但这样的事情应该有效:

using System.IO;

public Text highScoreText;

void Start() {
    highScoreText.text = File.ReadAllText(TEXTFILEPATH);
}

if (collision.tag != currentColor) {
    Debug.Log ("You Died");

    if (File.Exists(TEXTFILEPATH) {
        int highScore = int.TryParse(File.ReadAllText(TEXTFILEPATH);
        if(score > highScore) {
            File.WriteAllText(TEXTFILEPATH, score.ToString());
        }
    else {
        File.WriteAllText(TEXTFILEPATH, score.ToString());
    }
    }
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
score = 0;
}