NullReferenceException

I get “NullReferenceException: Object reference not set to an instance of an object
RPG.Combat.Fighter.Hit () (at Assets/Scripts/Combat/Fighter.cs:50)” error at the end of the video after editing the fighter.cs. The error points to the first line of the void Hit() method. Here is my code:

using UnityEngine;
using RPG.Movement;
using RPG.Core;

namespace RPG.Combat
{

    public class Fighter : MonoBehaviour, IAction
    {
        [SerializeField] float weaponRange = 2f;
        [SerializeField] float timeBetweenAttacks = 1f;
        [SerializeField] float weaponDamage = 5f;

        Transform target;
        float TimeSinceLastAttack = 0;

        private void Update()
        {
            TimeSinceLastAttack += Time.deltaTime;
            if(!target) return;
            bool isInRange = Vector3.Distance(transform.position, target.position) < weaponRange;
            if(!isInRange)
            {
                GetComponent<Mover>().MoveTo(target.position);

            }
            else
            {
                GetComponent<Mover>().Cancel();
                AttackBehaviour();
            }

        }

        private void AttackBehaviour()
        {
            if(TimeSinceLastAttack > timeBetweenAttacks)
            {
                // this will trigger the hit event;
                GetComponent<Animator>().SetTrigger("attack");
                TimeSinceLastAttack = 0;
                
            }
           
        }

        // animation event
        void Hit()
        {
            Health healthComponent = target.GetComponent<Health>();
            healthComponent.TakeDamage(weaponDamage);
        }

        public void Attack(CombatTarget combatTarget)
        {

            GetComponent<ActionScheduler>().StartAction(this);
            target = combatTarget.transform;

        }

        public void Cancel()
        {
            target = null;
        }

    }

}
1 Like

From my understanding,the target variable is null when the Hit() method is called. You should ensure that the target variable is properly assigned before calling the Hit() method.

Id try updating the code to this to have a null check:

void Hit()
{
    if (target == null)
    {
        Debug.LogWarning("Target is null in Fighter.Hit() method.");
        return;
    }
    
    Health healthComponent = target.GetComponent<Health>();
    healthComponent.TakeDamage(weaponDamage);
}

Everything remains the same except here you check to see if target is null and return, I’m hoping this helps you out.

Edit: this will help you return early and prevent the null reference exception, also make sure to verify that the target variable is properly set before calling the Hit() method in your game logic.

I for some reason don’t feel confident about this answer…

1 Like

Thank you for your reply! Your code solved the issue. Why do i need this logwarning? “You should ensure that the target variable is properly assigned before calling the Hit() method.” Not sure how to do that.

1 Like

Glad it helped, the log warning is good for debugging and troubleshooting, almost like a debug log it helps you find specific errors and bugs in your code, here is a list of reasons I found online to better explain:

Identifying the issue: When you encounter unexpected behavior or errors in your code, logging a warning can provide valuable information about what went wrong. In this case, if the target is null, it indicates that there might be an issue with setting the target properly before calling the Hit() method.

Debugging and troubleshooting: When you see the warning message in the console or log file, it helps you narrow down the source of the problem. You can trace back the code execution and check the logic that sets the target variable to determine why it is not being assigned correctly.

Tracking and monitoring: In larger projects or when working in a team, logging warning messages can be useful for tracking and monitoring issues. It allows you or your teammates to easily spot potential problems during development or testing phases.

While logging a warning message is not mandatory, it is considered a good practice because it helps in diagnosing issues more efficiently. Once you have identified and resolved the root cause of the problem, you can remove the warning or adjust it to better suit your debugging needs.

Hope this clears your questions about the log warning.

1 Like

Also your second question was only if the first bit didn’t solve your issue, I wasn’t even sure about the second part, glad this was solved on the first try😅

In this case, Hit() is an Animation Event, which means if you’re in the process of attacking, but the enemy dies before the hit finishes (or as a player, you click to move away and the blend from the Attack to Locomotion still fires the Hit()).

The Animation event merely fires and the Hit() responds to it. There’s no real need to log it out, as it’s just something that happens naturally. Null checking the Target in the beginning of Hit() and exiting (also known as Blocking) is the solution to the problem.

2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms