faint
faint
CC#
Created by faint on 6/27/2023 in #help
System.NullReferenceException in an if statement
I keep getting System.NullReferenceException directing me to the last if statement in the following code:
public override IEnumerable<Node> GetReachableNodes(TransformComponent xform, EntityQuery<NodeContainerComponent> nodeQuery, EntityQuery<TransformComponent> xformQuery,
MapGridComponent? grid, IEntityManager entMan)
{
if (grid == null)
yield break;

entMan.System<SpreaderSystem>().GetNeighbors(xform.Owner, Name, out _, out _, out var neighbors);

foreach (var neighbor in neighbors)
{
if (!nodeQuery.TryGetComponent(neighbor, out var nodeContainer) ||
!_nodeContainer.TryGetNode<SpreaderNode>(nodeContainer, Name, out var neighborNode))
{
continue;
}

yield return neighborNode;
}
}
public override IEnumerable<Node> GetReachableNodes(TransformComponent xform, EntityQuery<NodeContainerComponent> nodeQuery, EntityQuery<TransformComponent> xformQuery,
MapGridComponent? grid, IEntityManager entMan)
{
if (grid == null)
yield break;

entMan.System<SpreaderSystem>().GetNeighbors(xform.Owner, Name, out _, out _, out var neighbors);

foreach (var neighbor in neighbors)
{
if (!nodeQuery.TryGetComponent(neighbor, out var nodeContainer) ||
!_nodeContainer.TryGetNode<SpreaderNode>(nodeContainer, Name, out var neighborNode))
{
continue;
}

yield return neighborNode;
}
}
The problem is in _nodeContainer.TryGetNode.... After I moved TryGetNode from one place to another and added a new parameter, that error started appearing. Why does it always appear if all TryGetNode's parameters are nullable:
public bool TryGetNode<T>(NodeContainerComponent? component, string? identifier, [NotNullWhen(true)] out T? node) where T : Node
{
if (identifier == null || component == null)
{
node = null;
return false;
}

if (component.Nodes.TryGetValue(identifier, out var n) && n is T t)
{
node = t;
return true;
}

node = null;
return false;
}
public bool TryGetNode<T>(NodeContainerComponent? component, string? identifier, [NotNullWhen(true)] out T? node) where T : Node
{
if (identifier == null || component == null)
{
node = null;
return false;
}

if (component.Nodes.TryGetValue(identifier, out var n) && n is T t)
{
node = t;
return true;
}

node = null;
return false;
}
51 replies