Hi,
I’m having troubles with null reference exception when i try to load it shows this message
NullReferenceException: Object reference not set to an instance of an object
RPG.Combat.Fighter.EquipWeapon (RPG.Combat.Weapon weapon) (at Assets/Scripts/Combat/Fighter.cs:49)
using UnityEngine;
using RPG.Movement;
using RPG.Core;
using System;
using RPG.Saving;
using RPG.Attributes;
namespace RPG.Combat
{
public class Fighter : MonoBehaviour, IAction, ISaveable
{
[SerializeField] float timeBetweenAttacks = .5f;
[SerializeField] Transform rightHandTransform = null;
[SerializeField] Transform leftHandTransform = null;
[SerializeField] Weapon defaultWeapon = null;
Health target;
float timeSinceLastAttack = Mathf.Infinity;
Weapon currentWeapon = null;
private void Awake()
{
if (currentWeapon == null)
{
EquipWeapon(defaultWeapon);
}
}
private void Update()
{
timeSinceLastAttack += Time.deltaTime;
if (target == null) return;
if (target.IsDead()) return;
if (!GetIsInRange())
{
GetComponent<Mover>().MoveTo(target.transform.position, 1f);
}
else
{
GetComponent<Mover>().Cancel();
AttackBehaviour();
}
}
public void EquipWeapon(Weapon weapon)
{
currentWeapon = weapon;
Animator animator = GetComponent<Animator>();
weapon.Spawn(rightHandTransform, leftHandTransform, animator);
}
public Health GetTarget()
{
return target;
}
private void AttackBehaviour()
{
transform.LookAt(target.transform);
if (timeSinceLastAttack > timeBetweenAttacks)
{
// This will trigger the Hit() event.
TriggerAttack();
timeSinceLastAttack = 0;
}
}
private void TriggerAttack()
{
GetComponent<Animator>().ResetTrigger("stopAttack");
GetComponent<Animator>().SetTrigger("attack");
}
// Animation Event
void Hit()
{
if(target == null) { return; }
if (currentWeapon.HasProjectile())
{
currentWeapon.LaunchProjectile(rightHandTransform, leftHandTransform, target, gameObject);
}
else
{
target.TakeDamage(gameObject, currentWeapon.GetDamage());
}
}
void Shoot()
{
Hit();
}
private bool GetIsInRange()
{
return Vector3.Distance(transform.position, target.transform.position) < currentWeapon.GetRange();
}
public bool CanAttack(GameObject combatTarget)
{
if (combatTarget == null) { return false; }
Health targetToTest = combatTarget.GetComponent<Health>();
return targetToTest != null && !targetToTest.IsDead();
}
public void Attack(GameObject combatTarget)
{
GetComponent<ActionScheduler>().StartAction(this);
target = combatTarget.GetComponent<Health>();
}
public void Cancel()
{
StopAttack();
target = null;
GetComponent<Mover>().Cancel();
}
private void StopAttack()
{
GetComponent<Animator>().ResetTrigger("attack");
GetComponent<Animator>().SetTrigger("stopAttack");
}
public object CaptureState()
{
return currentWeapon.name;
}
public void RestoreState(object state)
{
string weaponName = (string) state;
Debug.Log($"RestoreState - {weaponName}");
Weapon weapon = Resources.Load<Weapon>(weaponName);
if(weapon == null)
{
Debug.Log($"The weapon was not found in Resources");
}
EquipWeapon(weapon);
}
}
}