Another null reference exception!

First of all, great course still! Love to see you back from the holidays. :slight_smile:

When clicking the game area without first clicking on a defender to build I get the following error:

“NullReferenceException: Object reference not set to an instance of an object
DefenderSpawner.AttemptToPlaceDefenderAt (Vector2 gridPos) (at Assets/Scripts/DefenderSpawner.cs:23)
DefenderSpawner.OnMouseDown () (at Assets/Scripts/DefenderSpawner.cs:12)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)”

It seems to be in this part of the code:

private void AttemptToPlaceDefenderAt(Vector2 gridPos)
{
    var StarDisplay = FindObjectOfType<StarDisplay>();
    int defenderCost = defender.GetStarCost();
    if (StarDisplay.HaveEnoughStars(defenderCost))
    {
        SpawnDefender(gridPos);
        StarDisplay.SpendStars(defenderCost);
    }
}

Any thoughts? :slight_smile:

Hi Josef,

These kind of problems occur when assumptions are made that objects will always exist and as you’ve seen in this case, they don’t.

From memory I believe this issue will only arise once, because after you have clicked on a defender there will also be one that has been set as the selected defender.

To resolve the issue you could wrap the code in a check to see if a defender has been selected or not, something like this;

private void AttemptToPlaceDefenderAt(Vector2 gridPos)
{
    if(defender)
    {
        var StarDisplay = FindObjectOfType<StarDisplay>();
        int defenderCost = defender.GetStarCost();
        if (StarDisplay.HaveEnoughStars(defenderCost))
        {
            SpawnDefender(gridPos);
            StarDisplay.SpendStars(defenderCost);
        }
    }
}

Whilst that would most likely prevent the error from occurring it’s a bit of a lazy way to resolve the problem in my opinion. We are effectively saying, “I know this will be null if the user clicks without first selecting a defender so I’ll protected against it”, as opposed to saying, “I know this will be null if the user clicks without first selecting a defender, so I’ll resolve the root cause issue”.

Taking the latter into account, setting a defender button to be pre-selected would mitigate this issue entirely, and make the buttons at the bottom of the screen make more sense as one would be shown highlighted from the beginning.

If you did go down the route of just wrapping it with a null check, it would probably be advantageous to give the player some affordance to the issue too, for example, play an audio clip so that the player hears a MERP and realises their mistake.

Hope the above helps :slight_smile:

3 Likes

Thanks for the help! :slight_smile:

1 Like

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

Privacy & Terms