【问题标题】:After Game Over how to stop score from increasing游戏结束后如何阻止分数增加
【发布时间】:2019-11-18 13:29:27
【问题描述】:

我正在制作一个无尽的跑步游戏,并且正在使用一个“ScoreManager”对象,并将一个 2d 盒对撞机设置为“触发”,每次对象击中它时都会增加分数。但如果健康达到 0,我希望它停止增加分数。这是 ScoreManager 代码:

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

但这似乎不起作用。

生命值显示在玩家脚本中。

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

有什么想法吗?

【问题讨论】:

  • if (other.CompareTag("Obstacle") &amp;&amp; currentHealth &gt; 0) { score++; } ?
  • 你什么时候换health?我不会在Update 中做这些事情,而是基于事件,例如在属性中。还有例如scoreDisplay.text = score.ToString(); 发生在 score 实际更改的那一刻就足够了
  • 在 scoreManager 脚本中'private void Update() { if (Input.GetKey(KeyCode.Space)) { Destroy(this); } ' 似乎工作。但它只会在按下键后删除游戏对象。我已将其更改为 (health

标签: c# unity3d 2d


【解决方案1】:

无论您的 health 是在哪里定义的,都可以将其替换为一个属性,该属性在设置为值

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多