Search code examples
c#xna

Pass a TouchCollection by reference


My main loop:

...

// Variables declaration
TouchCollection touch_;

...

private void InitializeAll()
{
     ...
     player = new Player(touch_);
     ...
}

protected override void Update(GameTime gametime)
{
    touch_ = TouchPanel.GetState();
    player_.Update(gametime);
    ...
}

I want to call TouchPanel.GetState(); just one time for every update, so I didn't put it also in player's update loop and in every other object's update loop that needs to know touch state. So I passed touch_ into player's constructor, but I doesn't work: player doesn't see any update of touch_ variable.

I understand that this is a problem related to the fact that touch_ is being assigned everytime.

How can I solve this?


Solution

  • I understand that this is a problem related to the fact that touch_ is being assigned every time.

    True, you are almost there. Overwriting the value of touch_ is ok, it's just the assumption that your player_ will receive the new values that is off.

    Remember that TouchPanel.GetState() returns a TouchCollection. This is a struct, which means that if you pass is as an argument (like in your constructor) it will be a copy of the object, not a reference to it.

    The super-simple way to fix this: pass the new values into your player_.Update() method every time.

    player_.Update(gametime, touch_);
    

    Now when your player updates, it will have fresh data to work with. You will have to thread your data around if you need it more complex.

    You may remove the argument from the player's constructor if you don't need it there as well.