Hello,
I am on Raycasting For Components of the 2019 RPG Core Combat Creator: Learn Intermediate Unity C# Coding.
I did the code as in the video but am getting a Null reference in my InteractWithCombat code in the PlayerController.
Here is what I am working with
PlayerController.cs :
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
public class Fighter : MonoBehaviour
{
public void Attack(CombatTarget target)
{
print(“Take that you short, squat peasant!”);
}
}
NullReferenceException: Object reference not set to an instance of an object
RPG.Control.PlayerController.InteractWithCombat () (at Assets/Scripts/Control/PlayerController.cs:25)
RPG.Control.PlayerController.Update () (at Assets/Scripts/Control/PlayerController.cs:11)
what is weird is that when I originally started the project a month or so ago this worked just fine, but now it is not working. I just cant see where I went wrong