我的游戏得分在某些点上递增!这工作正常,但是我想要保存高分并且不确定如何实现playerprefs,因为我仍然难以与Unity和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;
}
}
}
最佳答案
增加分数似乎没有任何问题。如果您想保存高分并使其在游戏中持续存在,建议您在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;
}
关于c# - 根据得分设置高分并在unity2D游戏中显示,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46057022/