Unity:PlayerLife变量在Inspector或HUD中不会明显更新,但在后台仍然可用

时间:2017-08-21 16:39:51

标签: c# unity3d hud

playerLife变量在检查器或屏幕上的运行状况文本中无法明显更新,但Player仍然死亡,因为playerLife降至零以下。

我已确定附加到Player GameObject的Zombie预制件仅为Player预制件而非场景内活动件Player。我如何制作它以便僵尸总是通过脚本引用场景中的活动播放器而不是基本的播放器预制件? (另外,它不允许我手动将活动播放器拖入僵尸中)

Call hierarchy for playerLife

public class Player : MonoBehaviour
{
    public RaycastHit hit;
    public int gunDamage = 1;
    public Zombie zombie;

    private float hitForce = 100f;
    public float playerLife;
    private Vector3 flareLower = new Vector3(0, -0.5f, 0);

    void Start()
    {
        spawnPoints = playerSpawnPoint.GetComponentsInChildren<Transform>();
        playerLife = 200;
    }

    void Update() //T-toggle
    {
        if (Input.GetButton("Fire1"))
        {
            LazerBeam();
        }

        if (reSpawn != lastToggle)
        {
            ReSpawn();
            reSpawn = false;
        }
        else
            lastToggle = reSpawn;
    }



    public void Life (float damage)
    {
        playerLife -= damage;
        if (playerLife <=0)
        {
            playerLife = 100;
            SceneManager.LoadScene(2);
        }
    }

}
public class Zombie : MonoBehaviour
{
    public int currentHealth;
    public Player player;
    public PlayerLifeCollider playerCollider; 
    private int damage;

    public void Damage(int damageAmount)
    {
        currentHealth -= damageAmount;
        if (currentHealth <= 0)
        {
            PlayerLifeCollider.instance.ObjectsInRange.Remove(gameObject);
            DestroyZombie();
        }
    }

    public void DestroyZombie()
    {
        Destroy(gameObject);
        // gameObject.SetActive(false);
    }

    public void DamagePlayer(float damage)
    {
         player.Life(damage);
    }
}

2 个答案:

答案 0 :(得分:0)

public void Damage(int damageAmount)
{
    currentHealth -= damageAmount;

    print(currentHealth);// will show in terminal if thats what you are asking


    if (currentHealth <= 0)
    {
        PlayerLifeCollider.instance.ObjectsInRange.Remove(gameObject);
        DestroyZombie();
    }
}

答案 1 :(得分:0)

正如你所说,问题是你没有引用你场景中的Player对象,而是一个预制的对象。为避免这种情况,您可以向Zombie脚本添加Start函数,并要求查找场景中唯一的Player实例。为此,您可以使用FindObjectOfType功能:

void Start()
{
    player = FindObjectOfType<Player>();
}

考虑到整个场景中只有一个Player脚本,您还可以在Player类中保存对Player实例的静态引用。

public class Player : MonoBehaviour
{
    private static Player _instance;

    public static Player Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType<Player>();
            }
           return _instance;
        }
    }

    // Reset of your class

}

然后,您可以在Zombie脚本中获取此引用:

public class Zombie : MonoBehaviour
{
    static Player player;

    void Start()
    {
        if(player == null)
        {
            player = Player.Instance;
        }
    }

    // Rest of your class content
}

这样,您只需使用Zombie脚本调用FindObjectOfType函数而不是每个对象一次。