恢复健康不会改变玩家的状态

时间:2019-08-01 18:18:05

标签: c# unity3d

我制造了一个拥有10点生命值的玩家。每次被击中都会失去1点生命。在健康栏中可以看到差异。为了让玩家有机会抵御一波又一波的敌人,我尝试重新创建“健康拾取”。

我编写了代码,使玩家得到了治愈,到目前为止,它在玩家经过图标时触发,但是由于某种原因,玩家没有得到治愈吗?

要利用所有这些,我有2个代码文档。

下面的第一个是运行状况提取器上添加的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class HealthPickup : MonoBehaviour
{
    Health health;

    public float healthBonus;

    void Awake()
    {
      health = FindObjectOfType<Health>();
    }

    void OnTriggerEnter2D(Collider2D other)
    {
      if(other.GetComponent<Player>() == null)
        return;

      if(health.health < health.maxHealth)
      health.health = health.health + (int)healthBonus;
      {
      Destroy(gameObject);
      }
    }
}

以下代码是玩家健康的代码。

    [Header ("Max/Starting Health")]
    public int maxHealth;
    [Header ("Current Health")]
    public int health;

void Start () {
        health = maxHealth;
    }

    public bool TakeHeal (int amount) {
        if (dead || health == maxHealth)
            return false;

        health = Mathf.Min (maxHealth, health + amount);

        if (OnTakeHealEvent != null)
            OnTakeHealEvent.Invoke();


        return true;
    }

正如您在下面看到的那样,我将奖励生命值设置为3。当玩家与对象碰撞时,会为玩家增加3生命值。 Adding health

您可以看到玩家共有10点生命值。我尝试减少游戏中的生命值并与该对象碰撞。然而,没有向用户增加健康。 Player health

您可以看到玩家现在有7点生命值(3.5巴) Player health

当我越过健康栏时,玩家的生命值(7)仍然保持不变。甚至对撞机和物体的破坏也完全起作用。 Player health

损坏播放器功能

    protected virtual void Awake () {
        if (Owner == null) {
            Owner = gameObject;
        }
    }

    public virtual void OnTriggerEnter2D(Collider2D collider)
    {           
        Colliding (collider);
    }

    public virtual void OnTriggerStay2D(Collider2D collider)
    {           
        Colliding (collider);
    }

    protected virtual void Colliding(Collider2D collider)
    {
        if (!isActiveAndEnabled) {
            return;
        }

        // if what we're colliding with isn't the target tag, we do nothing and exit
        if (!collider.gameObject.CompareTag(TargetTag)) {
            return;
        }

        var health = collider.gameObject.GetComponent<Health>();

        // If what we're colliding with is damageable / Has  health component
        if (health != null)
        {
            if(health.health > 0 && !health.invincible)
            {
                // Apply the Damage
                health.TakeDamage(DamageToCause);
            }

1 个答案:

答案 0 :(得分:4)

您不能保证您要修改/检查的Health实例与播放器附带的实例相同。因此,当与Player发生冲突时,您应该从与之碰撞的Health中获取Player组件。

此外,您已经在TakeHeal中检查是否有过度修复,因此可以重新使用该方法:

void OnTriggerEnter2D(Collider2D other)
{
    if(other.GetComponent<Player>() == null)
        return;

    health = other.GetComponent<Health>();

    if (health.TakeHeal((int)healthBonus))
    { 
        Destroy(gameObject); 
    }
}