0

I've been trying to figure out how to shoot a raycast out the front of my fist person camera and when it hits an object with the EnemyHealth script, it takes the desired amount of damage defined by the variable 'gunDamage'. I'm pretty sure I've been referencing the EnemyHealth script correctly and calling the TakeDamage function inside of the EnemyHealth script, but it keep throwing a nullreferenceexception error at me. I've been stumped on this for days and it's driving me mentally insane. I will gladly try to clear up any questions you have about the script or this post.

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

public class GunScript : MonoBehaviour
{
    EnemyHealth enemyHealth;
    [SerializeField] Camera FPCamera;
    [SerializeField] float range = 100f;
    public float gunDamage = 50f;

    void Awake()
    {
        enemyHealth = GetComponent<EnemyHealth>();
    }

    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Shoot();
        }
    }

    private void Shoot()
    {
        RaycastHit hitObject;
        if (Physics.Raycast(FPCamera.transform.position, FPCamera.transform.forward, out hitObject, range))
        {
            //Debug.Log("you hit a " + hitObject.transform.name);
            if (hitObject.transform.parent.GetComponent<EnemyHealth>() != null)
            {
                enemyHealth.TakeDamage(gunDamage);
            }
        }
        else
        {
            //null protector
            return;
        }
    }
}

using UnityEngine;

public class EnemyHealth : MonoBehaviour
{
    public float hitPoints = 100f;

    public void TakeDamage(float gunDamage)
    {
        print(hitPoints);

        hitPoints -= gunDamage;
        if (hitPoints <= 0)
        {
            Destroy(gameObject);
        }
    }
}

I tried to access the information about the object that the raycast collided with, determine if it had the EnemyHealth script on it, and run the TakeDamage function in the EnemyHealth script. The raycast suuccessfully collided with the objects that I was aiming at, but the object does not take damage. Instead it throws a nullreferenceexception.

1 Answers1

1

It looks like you’re trying to use a EnemyHealth component on the local GameObject, instead of the one on the enemy. Try this instead.

private void Shoot()
{
    if ( Physics.Raycast (FPCamera.transform.position, FPCamera.transform.forward, out var hitObject, range))
    {
        if (  hitObject.transform.parent.TryGetComponent<EnemyHealth> ( out var eh ) )
            eh.TakeDamage(gunDamage);
    }
    else
    {
        //null protector
        return;
    }
}
Milan Egon Votrubec
  • 3,696
  • 2
  • 10
  • 24