问题描述
我是一个新手,我正在制作这个 android 游戏,如果玩家摧毁了一颗流星,一个分数会被添加到它的分数中,问题是我想在我的 scoreText 中显示分数,但是每当我初始化它在我的 Update() 中,它迅速将分数添加到我的 scoreText 中。我只是不知道如何将分数正确添加到我的 scoreText 这是我的游戏管理器脚本
public class GameManager : MonoBehavIoUr
{
public static int displayscores;
public int displayThescore;
public Text scoreText;
// Start is called before the first frame update
void Start()
{
scoreText.text = "" + displayscores;
}
void Update(){
scoreText.text = "" + displayscores;
displayscores += Meteor.displayscore;
}
}
这是制作条件的脚本,如果流星被摧毁,则根据对流星的命中,将分数添加到 displayscore
public class Meteor : MonoBehavIoUr
{
public int maxHealth;
public int currentHealth;
public float speed;
public int hits = 0;
public int score = 100;
public static int displayscore;
public int display;
public int currentHealthChecker;
public static int counter;
public Health healthBar;
public GameObject canvas;
public Transform effect;
// Start is called before the first frame update
void Start()
{
currentHealth = maxHealth;
healthBar.setMaxHealth(maxHealth);
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector2.down * speed * Time.deltaTime);
}
public void OnTriggerEnter2D(Collider2D other){
if(other.transform.tag == "bullet"){
hits++;
canvas.SetActive(true);
currentHealth--;
currentHealthChecker = currentHealth;
healthBar.setHealth(currentHealth);
display = displayscore;
if(currentHealth <= 0){
displayscore = score * hits;
Instantiate(effect,other.transform.position,other.transform.rotation);
Destroy(this.gameObject);
counter++;
canvas.SetActive(false);
}
Destroy(other.gameObject);
}
if(other.transform.tag == "bottom"){
Destroy(this.gameObject);
}
}
}
解决方法
您正在使用 update 方法进行初始化,这就是为什么它会不断快速添加的原因,因为每帧都会调用 update。不是在 update 中加入,而是在 ontriggerenter2d 方法中加入分数值。
public void OnTriggerEnter2D(Collider2D other){
if(other.transform.tag == "bullet"){//add score}