Null Reference Exception - Again

Hey there,

I always seem to run into this error and have come across it once again in this part of the course.

Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DefenderSpawner : MonoBehaviour
{

    [SerializeField] GameObject defender;

    private void OnMouseDown()
    {
        SpawnDefender(GetSquareClicked());
    }

    private Vector2 GetSquareClicked()
    {
        Vector2 clickPos = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
        Vector2 worldPos = Camera.main.ScreenToWorldPoint(clickPos);
        return worldPos;
    }

    private void SpawnDefender(Vector2 worldPos)
    {
        GameObject newDefender = Instantiate(defender, worldPos, Quaternion.identity) as GameObject;
    }
}

A screen grab of Unity (error bottom left):

I seem to run into this error a lot and I guess I just haven’t quite grasped what is happening with the Null Reference Exception errors. Any help would be awesome.

thanks,
Dylan

Hi Dylan,

NullReferenceException means that a reference (“link”) to an instance is missing. Double click on the error message to see to which line in your code it is referring. If you exposed a field in the Inspector, make sure that it’s not empty.


See also:

My camera wasn’t tagged with MainCamera for some reason. grrrr…

thanks,
Dylan

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

Privacy & Terms