After Game Over how to stop score from increasing

∥☆過路亽.° 提交于 2020-01-25 00:19:09

问题


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();

}

I would like to add a:

public int health = 3; 

and in the Update function:

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

But that doesn't seem to work.

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);
    }    

Any thoughts?


回答1:


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.
    }
}


来源:https://stackoverflow.com/questions/58915703/after-game-over-how-to-stop-score-from-increasing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!