0

I'm creating a method that moves a sprite across the screen depending on what key is pressed

class InputController
{
    public void DetectInput (Vector2 position)
    {
        if (Keyboard.GetState().IsKeyDown(Keys.W))
        {
            position.Y -= 1;
        }

        if (Keyboard.GetState().IsKeyDown(Keys.S))
        {
            position.Y += 1;
        }

        if (Keyboard.GetState().IsKeyDown(Keys.A))
        {
            position.X -= 1;
        }

        if (Keyboard.GetState().IsKeyDown(Keys.D))
        {
            position.X += 1;
        }

Trying to call if from my other class, I get an error:

System.NullReferenceException: 'Object reference not set to an instance of an object

InputController was null

Here is the relevant code from the other class

private InputController InputController;

protected override void Update(GameTime gameTime)
{
    InputController.DetectInput(_position);
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

2

Your problem is that InputController == null. Probably somewhere in your code, this isn't being run:

InputController = new InputController();
Robyn
  • 1,334
  • 10
  • 12
  • Ah I seee so I have to decare in my Update method that "InputController = new InputController();" Thank you – JumboShrimpPhD Mar 04 '21 at 05:05
  • It doesn't strictly have to be created in the Update method, but you do have to create an InputController at some point before you use InputController.DetectInput – Robyn Mar 04 '21 at 05:08