-1

Edit: this is not a duplicate, I know what a NullReferenceException means.

The following code is giving me a NullReferenceException for "target" right after a null check:

private Entity  target;
private float   newPathTimer;
private float   attackTimer;

public override void Update(float deltaTime) {
    attackTimer += deltaTime;
    // Check for target
    if (target != null) {
        float   distance    = MathExtra.PointDistance(Entity.X, Entity.Y, target.X, target.Y);

The only places where "target" is set:

public override void Receive(ICommand message) {
    if (message is Attack) {
        target          = SystemMessager.SendQuery<Entity>(new GetEntity(((Attack)message).entityID));
        newPathTimer    = NEW_PATH_RATE;
    }
    if (message is FollowPath) {
        if (!((FollowPath)message).pursuit) {
            target = null;
        }
    }
}

All references to "target":

enter image description here

If it makes any difference, this application is a server that receives and sends packets to clients.

Also, I don't know how to reproduce this error, it doesn't happen all the time.

Edit: The receive method is called every time a certain packet is received. I think packets may be received on a separate thread causing this issue.

Bellum
  • 3
  • 3

1 Answers1

0

Your issue appears to be a lack of locking or synchronisation around the target field.

Given as you have said this is being called on multiple threads when packets are received then you could use lock to guard access to it whenever you read and write to it. Or, it's probably more likely that you are not intending to share the instance of this class and other fields within it, so you may need to look at changing the lifetime of these instances.

Stuart
  • 5,358
  • 19
  • 28