Unreachable Code warning and NullReference Exceptions

Hello, I’m on Lecture 17 working on the Level grid. My code was working until I hit the point of trying to transform everything into a UnitList. Once I started trying to run it I now have a ton of errors and I’m not sure why! I even went as far as copy pasting all changed files from the gitlab trying to figure out exactly which file was causing the error.

Here are the errors I’m looking at.

Here is GridDebugObject.cs

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

public class GridDebugObject : MonoBehaviour
{

    [SerializeField] private TextMeshPro textMeshPro;


    private GridObject gridObject;

    public void SetGridObject(GridObject gridObject)
    {
        this.gridObject = gridObject;
    }

    private void Update()
    {
        textMeshPro.text = gridObject.ToString();
    }

}

Help?

The ‘unreachable code’ comes from GridObject.cs can you show us that script?

The NRE is from this script (GridDebugObject) and suggests either the textMeshPro field has not been assigned in the inspector, or the gridObject has not been set. I suspect it’s the latter and fixing the unreachable code will also fix this. But I wouldn’t know without seeing the GridObject script

GridObject.cs

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

public class GridObject
{

    private GridSystem gridSystem;
    private GridPosition gridPosition;
    private List<Unit> unitList;

    public GridObject(GridSystem gridSystem, GridPosition gridPosition)
    {
        this.gridSystem = gridSystem;
        this.gridPosition = gridPosition;
        unitList = new List<Unit>();
    }

    public override string ToString()
    {
        return gridPosition.ToString();
        string unitString = "";
        foreach (Unit unit in unitList)
        {
            unitString += unit + "\n";
        }

        return gridPosition.ToString() + "\n" + unitString;
    }

    public void AddUnit(Unit unit)
    {
        unitList.Add(unit);
    }

    public void RemoveUnit(Unit unit)
    {
        unitList.Remove(unit);
    }

    public List<Unit> GetUnitList()
    {
        return unitList;
    }

}

The unreachable code is here (marked above). You are returning out of the method, so none of the code below it in that function will run, so it’s ‘unreachable’.

Doesn’t explain the NRE. Check that you have assigned the text field in the inspector and that you are actually calling SetGridObject(...) in the GridSystem when you create the grid debug objects

1 Like

Ah, I didn’t see it marked in red on the gitlab. Thank you for saving me from my oversight!

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

Privacy & Terms