Adding and removing specific components to a list based OnTriggerEnter/Exit, Getting Null Exceptions

Here’s the code in question:

void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.GetComponentInParent<Room>()) 
    {
        r = other.gameObject.GetComponentInParent<Room>();
        camGoto = true;
        if (!colList.Contains(other))
            colList.Add(other);
    }
}
void OnTriggerExit2D(Collider2D other)
{
    if (other.gameObject.GetComponentInParent<Room>())
    {
        if (colList.Contains(other))
            colList.Remove(other);
    }
}

Upon starting the game I get a bunch of “NullReferenceException: Object reference not set to an instance of an object
PlayerController.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/PlayerController.cs:63)” (presumably because those objects didn’t get their parent set yet?). When I collide with something else (in my case another player, only without the controller script) I get those errors again, also for the Exit this time.

Any explanation why this is happening/how to fix it? Everything seems to work despite the errors but it doesn’t feel right just letting them be.

The only thing that could really cause a Null ref exception here is your “colList”. Are you sure you created an instance of your List?

So does your declaration looks like this:

List<Collider2D> colList;

or like this:

List<Collider2D> colList = new List<Collider2D>();

The latter would be correct. In the first case you only declared a variable that can hold an instance of a generic list but initially contains null;