NullReferenceException: Object reference not set to an instance of an object

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

Hi @Kameen_Avery, I can’t seem to see any issues with the code from what I gather GetComponent().Attack(target); is line 25, does the gameObject with the PlayerController have a Fighter on it?

Hey there, so Fighter is attached to the Player along with CombatTarget attached to the Enemy.

I even went as far as to copy paste the code from Github to see if that would work no dice.

I am not even allowed to move anywhere. Movement is completely dead.

So, after moving on to the next video, I realize that he corrects this later in the video Canceling Combat with Movement.

What really sucks is I spent a day trying to figure out where I went wrong and could not figure it out. This bodes ill for my future debugging…

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