Unity - 我的GameOverManager中的NullReferenceException

时间:2018-02-17 16:13:43

标签: unity3d nullreferenceexception

我试图加载我的" PlayerHealth"脚本到我的" GameOverManager"从PlayerHealth-Script检查我的currentHealth。

如果当前的健康状况是" 0" - 我想触发动画。

问题是,Unity给出了以下消息的错误:

" NullReferenceException:对象引用未设置为对象的实例 GameOverManager.Update()(在Assets / GameOverManager.cs:32)"

以下是我的GameOverManager代码:

public class GameOverManager : MonoBehaviour {

    public PlayerHealth playerHealthScript;
    public float restartDelay = 5f;
    Animator anim;
    float restartTimer;

    private void Awake()
    {
        anim = GetComponent<Animator>();
    }

    private void Update()
    {
        playerHealthScript = GetComponent<PlayerHealth>();
        if (playerHealthScript.currentHealth <= 0) {
            anim.SetTrigger("GamerOver");
            restartTimer += Time.deltaTime;
            if (restartTimer >= restartDelay) {
                SceneManager.LoadScene(2);
            }
        }       
    }
}

错误在以下行触发:

if (playerHealthScript.currentHealth <= 0)

这是层次结构 - FPSController持有&#34; PlayerHealth&#34; - HUDCanvas持有&#34; GameOverManager:

enter image description here

以下是检查员:

enter image description here

enter image description here

以下是&#34; PlayerHealth&#34;的代码:

  using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;

public class PlayerHealth : MonoBehaviour
{
    public int startingHealth = 100;                            // The amount of health the player starts the game with.
    public int currentHealth;                                   // The current health the player has.
    public Slider healthSlider;                                 // Reference to the UI's health bar.
    public Image damageImage;                                   // Reference to an image to flash on the screen on being hurt.
    public AudioClip deathClip;                                 // The audio clip to play when the player dies.
    public float flashSpeed = 5f;                               // The speed the damageImage will fade at.
    public Color flashColour = new Color(1f, 0f, 0f, 0.1f);     // The colour the damageImage is set to, to flash.

    public float restartDelay = 5f;

   //Animator anim;                                              // Reference to the Animator component.
    public AudioSource playerAudio;                                    // Reference to the AudioSource component.
  //  PlayerMovement playerMovement;                              // Reference to the player's movement.
  //  PlayerShooting playerShooting;                              // Reference to the PlayerShooting script.
    bool isDead;                                                // Whether the player is dead.
    bool damaged;                                               // True when the player gets damaged.

void Awake()
{
    // Setting up the references.
  //  anim = GetComponent<Animator>();
 //   playerAudio = GetComponent<AudioSource>();
//    playerMovement = GetComponent<PlayerMovement>();
//    playerShooting = GetComponentInChildren<PlayerShooting>();

    // Set the initial health of the player.
    currentHealth = startingHealth;


}


void Update()
{
    // If the player has just been damaged...
    if (damaged)
    {
        // ... set the colour of the damageImage to the flash colour.
       damageImage.color = flashColour;
    }
    // Otherwise...
    else
    {
        // ... transition the colour back to clear.
       damageImage.color = Color.Lerp(damageImage.color, Color.clear, flashSpeed * Time.deltaTime);
    }

    // Reset the damaged flag.
    damaged = false;


    }




public void TakeDamage(int amount)
{
    // Set the damaged flag so the screen will flash.
    damaged = true;

    // Reduce the current health by the damage amount.
    currentHealth -= amount;

    playerAudio.Play();

    Debug.Log("PLayer Health: " + currentHealth);

    // Set the health bar's value to the current health.
    healthSlider.value = currentHealth;

    // Play the hurt sound
    playerAudio.Play();

    // If the player has lost all it's health and the death flag hasn't been set yet...
    if (currentHealth <= 0 && !isDead)
    {
        // ... it should die.
        Death();
    }
}


void Death()
{
    // Set the death flag so this function won't be called again.
    isDead = true;

    Debug.Log("In der Death Funktion");

1 个答案:

答案 0 :(得分:2)

首先,你不需要,或者更好,你不应该在GetComponent内使用Update,这是一种非常慢的方法,它会对性能产生很大的影响

所以,将代码更改为:

public class GameOverManager : MonoBehaviour {

    public PlayerHealth playerHealthScript;
    public float restartDelay = 5f;
    private Animator anim;
    private float restartTimer;

    private void Awake() {
        anim = GetComponent<Animator>();
        //No need for GetComponent<PlayerHealth>() if you assign it in the Inspector
        //playerHealthScript = GetComponent<PlayerHealth>();
    }

    private void Update() {
        if (playerHealthScript.currentHealth <= 0) {
            anim.SetTrigger("GamerOver");
            restartTimer += Time.deltaTime;
            if (restartTimer >= restartDelay) {
                SceneManager.LoadScene(2);
            }
        }
    }
}

此外,您的错误很可能是因为在Inspector中您为playerHealthScript变量分配了包含PlayerHealth脚本的游戏对象。但是,因为您尝试再次Update来获取脚本组件,但这次是来自具有GameOverManager脚本的游戏对象(我认为它没有PlayerHealth你得到NullReference,因为在这个游戏对象上找不到该脚本。

因此,正如您在我的代码中注释掉的两行中所看到的那样,您实际上并不需要从脚本中获取该组件,只需通过Inspector分配它,您就可以了。< / p>