C# - Godot keeps sending System.NullReferenceException error in the console even with checking

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By raviolicheddar

Hello,

I’m currently running into a probably dumb issue, however I can’t find a way to fix it out.
I have a code that is supposed to check for all other colliders of one type colliding with the object (A CharacterBody2D) after a timer timeout signal was sent. The code looks like this :

public void OnStopTimerTimeout()
{
      for (int i = 0; i < GetSlideCollisionCount(); i++)
           if (GetSlideCollision(i).GetCollider() is Unit unitCollider)
                foreach(Unit unit in SelectionGroup)
                     if (unit == unitCollider && (unitCollider.SelectionGroup == null || !unitCollider.SelectionGroup.Contains(this)))
                        // Colliding with another unit in the same group - DO SOMETHING HERE
}

This piece of code works as intended in the game - called after a timer has stopped, checks if there is current collision on the CharacterBody2D. In that case, loop through all collider, and check if we can cast them as the type “Unit”. If we can, check if the colliding unit is in the same SelectionGroup. If so, do something.

The issue is that the line systematically return an error : System.NullReferenceException, object reference not set as an instance of object. The object in question is the “unitCollider” (line bellow)

if (GetSlideCollision(i).GetCollider() is Unit unitCollider)

It’s not the if statement that’s failing : the if statement returns true, but using the var unitCollider will cast an error in the debuger. I can however do GD.Print(unitCollider), and will get a CharacterBody2D printed in the console.

I’ve also tried casting the type like this :

if (GetSlideCollision(i).GetCollider() is Unit)
{
	Unit unitCollider = (Unit)GetSlideCollision(i).GetCollider();
	// Rest of the code here
}

This, however, result in the same error.

So I’m not really sure of what is causing Godot to call the error over and over again. There is no other collider as those of the units so far, so it shouldn’t even be that the collider doesn’t have the Unit script. Plus, that’s also checked in the if condition…

Tested with godot beta 16, haven’t got any issues.

zeludtnecniv | 2023-01-31 11:47