Object reference not set to an instance of an object.

Hi, I have a problem, I need help with how to implement the TakeDamage method from the PlayerHealth script into the Bullet script.

Error is NullReferenceException: Object reference not set to an instance of an object Bullet.HitTarget().

public class Bullet : MonoBehaviour
{
    private Transform target;
    public float speed = 70f;
   
    public void Seek(Transform _target)
    {
        target = _target;
    }

    void Update()
    {
        if (target == null)
        {
         
             
           
            
          

           
        }


        Vector3 dir = target.position - transform.position;
        float distanceThisFrame = speed * Time.deltaTime;

        if (dir.magnitude <= distanceThisFrame)
        {
            HitTarget();
            return;
        }

        transform.Translate(dir.normalized * distanceThisFrame, Space.World);



    }
   
   


    public void HitTarget()
    {


      [B]  GetComponent<PlayerHealth>().TakeDamage();[/B]


        Debug.Log("Hit");
        Destroy(gameObject);

    }

  


}
public class PlayerHealth : MonoBehaviour
{

    public int health;
    public int numOfHearts;
    public Image[] hearts;
    public Sprite fullHearth;
    public Sprite emptyHearth;


    // Update is called once per frame
    void Update()
    {
        if (health < 0)
        {

            gameObject.SetActive(false);
        }


        if (health > numOfHearts)
        {
            health = numOfHearts;
        }


        for(int i=0; i< hearts.Length; i++)
        {

            if (i < health)
            {
                hearts[i].sprite = fullHearth;
            }
            else
            {
                hearts[i].sprite = emptyHearth;
            }





            if (i < numOfHearts)
            {
                hearts[i].enabled = true;
            }
            else
            {
                hearts[i].enabled = false;
            }

        }


        if (health < 1 )
        {

            Application.Quit();
          
            Debug.Log("Die");
        }


    }

  


    public void TakeDamage()
    {

        health--;

    }

}

Did you add the PlayerHealth script to the bullet gameobject (in the inspector) ?

I don’t think you understand me. PlayerHealth script is in the player and i need to take damage from the bullet. Do you know another way?

There is no other way. The answer is always the same… ALWAYS. It is the single most common error ever. Don’t waste your life on this problem. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

This is the kind of mindset and thinking process you need to bring to this problem:

https://discussions.unity.com/t/814091/4

Step by step, break it down, find the problem.

How to understand errors in general:

https://discussions.unity.com/t/824586/8

What you need is to make sure there is a collider set to trigger on the player / player hitbox script.

On the bullet you need a OnTriggerEnter to start the event and access the Damage function within the player health / player hitbox.

This is an example from my environmental damage script.

When the bullet comes into contact with the players hitbox, then you trigger the damage source. It gets the PlayerHitbox from ‘other’ which is the object that came into contact with the collider on the same object as the damage source script.

From there it executes the .DamageKnockback function within the PlayerHitbox script, parsing in values to the function that are specific to that source of damage.

    private void OnTriggerEnter2D(Collider2D other)
        {
            if (other.tag == "PlayerHitbox" && other.isTrigger)
            {
                PlayerHitbox player = other.GetComponent<PlayerHitbox>();

                Debug.Log("Player not null");
                Vector3 knockbackDir = (player.GetPosition() - transform.position).normalized;
                player.DamageKnockback(knockbackDir, knockbackTime, damageAmount);
            
            }
        }
    }

You could put an on trigger enter on the bullet. Check that the player hitbox != null.
Then grab the Player/player health script you’ve made and call its damage function.

Don’t know if that helps at all

public class Bullet : MonoBehaviour
{
    private Transform target;
    public float speed = 70f;

    public void Seek(Transform _target)
    {
        target = _target;
    }

    void Update()
    {
        Vector3 dir = target.position - transform.position;
        float distanceThisFrame = speed * Time.deltaTime;
        transform.Translate(dir.normalized * distanceThisFrame, Space.World);
    }


    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Player" && other.isTrigger)
        {
            int bulletDamage = 10; //Make a variable for this
            PlayerHealth playerHealth = other.GetComponent<PlayerHealth>();
            playerHealth.TakeDamage(bulletDamage);

        }
    }
}
// In player health you would need something like this
public void TakeDamage(int _tempDamage)
{
    health -= _tempDamage;
}

I’d do it more like that, with colliders and on trigger enter