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;
}
}
}