Forum begins after the advertisement:


[Part 4] NullReferenceException: OnTriggerEnter2D

Home Forums Video Game Tutorial Series Creating a Rogue-like Shoot-em Up in Unity [Part 4] NullReferenceException: OnTriggerEnter2D

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #15517
    isaac795
    Level 2
    Participant
    Helpful?
    Up
    0
    ::

    When my weapon hit the enemy it showed this error. I tried using Debug.Log(“Enemy health:” + enemyData.Maxhealth) at EnemyController script and yes it shows the enemy health next I’m using Debug.Log(“Enemy take damage: ” + currentDamage) and at ProjectileWeaponBehavior script and it shows enemy take the damage. But I tried to Debug.Log(“Enemy: ” + enemy) but it showed nothing. What do I miss 🤔🤣

    #15518
    isaac795
    Level 2
    Participant
    Helpful?
    Up
    0
    ::
    <code>protected virtual void OnTriggerEnter2D(Collider2D col)     //col = collider
        {
    
            if (col.CompareTag("Enemy"))
            {
                EnemyStats enemy = col.GetComponent<EnemyStats>();
                Debug.Log("Enemy: " + enemy);
                enemy.TakeDamage(currentDamage);   <== Error Here 
                Debug.Log("Enemy take damage: " + currentDamage);
            }
        }</code>
    #15519
    isaac795
    Level 2
    Participant
    Helpful?
    Up
    0
    ::

    I already set a tag as “Enemy”

    https://imgur.com/a/6Rc8RMA
    #15520
    isaac795
    Level 2
    Participant
    Helpful?
    Up
    0
    ::

    Here’s TakeDamage function

    <code>
    void Awake()
        {
           currentHealth = enemyData.Maxhealth;
        }
    public void TakeDamage(float dmg)
        {
    
            currentHealth -= dmg;
            if (currentHealth <= 0)
            {
                Dead();          <== Destroy game object
            }
        }</code>
    #15534
    Terence
    Level 30
    Keymaster
    Helpful?
    Up
    0
    ::

    isaac, the error is caused by this line:

    EnemyStats enemy = col.GetComponent<EnemyStats>();

    If the line fails to find an EnemyStats component, then the enemy variable will be empty. This is why enemy.TakeDamage() has an error, because it evaluates to null.TakeDamage().

    Check that the enemy prefabs in your game all have an EnemyStats component.

    #15542
    isaac795
    Level 2
    Participant
    Helpful?
    Up
    0
    ::

    You correct bro. ty

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: