GetComponent returning NullReferenceException

Hi, i’m a bit new to unity scripting and I have what seems to be a simple problem, but i can’t figure out the cause for the life of me. I have a script to change a float in a different using OverlapCircles and GetComponent. My main problem is I have it working in the beginning of my script for the damage and knockback but I tried duplicating it and affecting a different script and now it can’t reference an object. I can’t tell if i’m just missing something

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

public class playerattack : MonoBehaviour
{

    private float TimeBtwAttack;
    public float StartTimeBtwAttack;

    public Transform attackpos;
    public LayerMask whatisenemy;
    public LayerMask whatisresource;
    public float attackrange;
    public int damage;
    public float thrust;
    public int gatheramount;

    private void Update()
    {
        if(TimeBtwAttack <= 0)
        {
            if (Input.GetKey(KeyCode.E))
            {

                Collider2D[] enemiesToDamage = Physics2D.OverlapCircleAll(attackpos.position, attackrange, whatisenemy);
              
                for (int i = 0; i < enemiesToDamage.Length; i++)
              
                {
                    enemiesToDamage[i].GetComponent<Enemyhealth>().TakeDamage(damage);
                    enemiesToDamage[i].GetComponent<Enemyhealth>().Knockback(thrust);
                }

                Collider2D[] resource = Physics2D.OverlapCircleAll(attackpos.position, attackrange, whatisresource);
                for (int i = 0; i < resource.Length; i++)
                {
                    resource[i].GetComponent<playerhealth>().Gather(gatheramount);// this is what is returning null 
                }

            }
            TimeBtwAttack = StartTimeBtwAttack;
        }
        else
        {
            TimeBtwAttack -= Time.deltaTime;
        }
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(attackpos.position, attackrange);
    }

}

.

Can you say what line the null reference is on? From your post you said the first part works so I’m assuming the GetComponent() on line 38 isn’t working? If so I would probably say check your spelling of playerhealth and make sure that the script is on the parent of the object that gets detected with your overlapcircle method.

Your resource target has a playerhealth component on it? I’m guessing this isn’t correct and you have one playerhealth on your player. Which means you need to get that component.

ah, thank you the script I was trying to affect wasn’t parented to the object found. I was trying to affect the player when the object was hit instead of the actual object itself. Simple problem, simple solution.

1 Like