NullReferenceException 玩家健康执行期间

问题描述 投票:0回答:0

我正在尝试建立玩家的生命值,当敌人攻击玩家时,生命值会减少。一切正常,直到我创建画布到 UI 滑块然后我收到以下错误:

NullReferenceException: Object reference not set to an instance of an object
PlayerHealth.DecreaseHealth (System.Int32 amountOfHealth) (at Assets/Scripts/PlayerHealth.cs:21)
DestroyPlayer.OnTriggerEnter (UnityEngine.Collider collision) (at Assets/Scripts/DestroyPlayer.cs:29

我原以为滑块会减小,但出现 NullReferenceException 错误。

在 PlayerHealth.cs 中,我的代码如下所示:

 public Slider health_Slider;
 private int Health;
 private const int MAX_HEALTH = 100;

public void DecreaseHealth(int amountOfHealth)
    {
        Health -= amountOfHealth;
        health_Slider.value = Health;

        if (Health <= 0)
        {
            //Player is dead
            Destroy(gameObject);
            Debug.Log("you are dead");
        }
    }

在 PlayerDestroy.cs 上,代码如下:

//OnTriggerEnter: To avoid displacement of the player when the bullet hit him
    private void OnTriggerEnter(Collider collision)
    {
      if (collision.gameObject.CompareTag("EnemyBullet"))
        {
            // Destory bullet
            Destroy(collision.gameObject);

            playerHealth.DecreaseHealth(10);
        }
    }

有什么建议可以解决这个错误吗?

c# unity3d unityscript
© www.soinside.com 2019 - 2024. All rights reserved.