The code seems to get passed the “continue” command and execute the attack on a target but it does not find a target (null reference). I have added the combat target component to the enemy and checked over all the code against the github and the tutorial many times. I can’t figure out what’s wrong. Any help would be greatly appreciated.
NullReferenceException: Object reference not set to an instance of an object
RPG.Control.PlayerController.InteractWithCombat () (at Assets/Scripts/Control/PlayerController.cs:28)
RPG.Control.PlayerController.Update () (at Assets/Scripts/Control/PlayerController.cs:12)
PlayerController.cs
using UnityEngine;
using RPG.Movement;
using RPG.Combat;
namespace RPG.Control
{
public class PlayerController : MonoBehaviour
{
private void Update()
{
InteractWithCombat();
InteractWithMovement();
}
private void InteractWithCombat()
{
RaycastHit[] hits = Physics.RaycastAll(GetMouseRay());
foreach (RaycastHit hit in hits)
{
CombatTarget target = hit.transform.GetComponent<CombatTarget>();
if (target == null) continue;
if(Input.GetMouseButtonDown(0))
{
GetComponent<Fighter>().Attack(target);
}
}
}
private void InteractWithMovement()
{
if (Input.GetMouseButton(0))
{
MoveToCursor();
}
}
private void MoveToCursor()
{
RaycastHit hit;
bool hasHit = Physics.Raycast(GetMouseRay(), out hit);
if (hasHit)
{
GetComponent<Mover>().MoveTo(hit.point);
}
}
private static Ray GetMouseRay()
{
return Camera.main.ScreenPointToRay(Input.mousePosition);
}
}
}
Fighter.cs
using UnityEngine;
namespace RPG.Combat
{
public class Fighter : MonoBehaviour
{
public void Attack(CombatTarget target)
{
print("Take that you short, squat peasant!");
}
}
}
CombatTarget.cs
using UnityEngine;
namespace RPG.Combat
{
public class CombatTarget : MonoBehaviour
{
}
}