0

I keep getting this message:

An unhandled exception of type 'System.NullReferenceException' on the code below:

        if (position.X >= p.position.X && position.X != p.position.X)
            position.X -= Yspeed;
        if (position.X >= p.position.X && position.X != p.position.X)
            position.X += Yspeed;
        position.Y = position.Y + Yspeed;

Specifically refers to the first line. What i'm trying to do is move the enemy towards the player.

1 Answer 1

1

You are accessing a field or method of a null reference:

MyType instance = null;

// Throws a NullReferenceException because instance is 
// not an actual object but null.
instance.Name = "foo";

So I suppose position or, rather p is unset. If you are using an IDE like Visual Studio use a breakpoint and inspect your variables and check if they actually contain something.

Sign up to request clarification or add additional context in comments.

2 Comments

It would have to be p if position is a Vector2. Structs are always initialized to a default value.
Yes, yet we don't actually see the declaration of position nor the type definition. It could just as well be a class. But I'm fairly certain that you are right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.