游戏结束后如何阻止分数增加 [英] After Game Over how to stop score from increasing

查看:116
本文介绍了游戏结束后如何阻止分数增加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作无尽的亚军游戏,并且正在使用 ScoreManager对象,并且将对撞机2d设置为触发,因此每次对象被击中时得分都会提高。但是我希望它在健康状况达到0时停止增加分数。这是ScoreManager代码:

Im making a endless runner game and am using a 'ScoreManager' object with a box collider 2d set to 'is trigger' increasing the score every time a object hits it. But I want it to stop increasing the score if the health reaches 0. This is the ScoreManager code:

 public int score;
public Text scoreDisplay;

void OnTriggerEnter2D(Collider2D other)
{
    if (other.CompareTag("Obstacle"))
    {
        score++;
    }
}

private void Update()
{
    scoreDisplay.text = score.ToString();

}

我想添加一个:

public int health = 3; 

并在更新功能中:

if (health <= 0) {
        Destroy(gameObject);
    } 

但这似乎不起作用。

运行状况显示在播放器脚本中。

The health is displayed in a player script.

public class Player : MonoBehaviour
{
private Vector2 targetPos;
public float Yincrement;

public float speed;
public float maxHeight;
public float minHeight;

public Text healthDisplay;

public GameObject gameOver;

public int health = 3;
// Start is called before the first frame update
void Start()
{

}

// Update is called once per frame
private void Update()
{
    healthDisplay.text = health.ToString();

    if (health <= 0) {
        gameOver.SetActive(true);
        Destroy(gameObject);
    }    

有什么想法吗?

推荐答案

只要定义了健康状况,就将其替换为一个属性,该属性会在设置为值<时启动一个事件。 0.像这样:

Wherever your health is defined, substitute it by a property that launches an event whenever set to a value < 0. Like this:

public class Player : MonoBehavior
{
    public delegate void PlayerDiedDelegate();
    public static event PlayerDiedDelegate onPlayerDied;

    private int _health;
    public int health
    {
        get
        {
            return _health;
        }
        set
        {
            _health = value;
            if(_health < 0)
            {
                onPlayerDied?.Invoke();
            }
        }
    }
}

现在您可以将场景中的任何控制器附加到事件:

Now you can attach any controller in your scene to the event:

public class ScoreController : MonoBehavior
{
    private void Awake()
    {
        Player.onPlayerDied += OnPlayerDied;
    }

    private void OnPlayerDied()
    {
        // Put your logic here: stop collecting score etc.
    }
}

这篇关于游戏结束后如何阻止分数增加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆