0

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?

Francesco Bonizzi
  • 5,142
  • 6
  • 49
  • 88
  • 1
    What is the datatype of `touch_`? If it's a struct, I can understand why it does not work. (yes, it [is a struct](http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.touch.touchcollection.aspx)) – gunr2171 Jul 14 '14 at 16:41
  • @gunr2171 So how can I solve the problem? – Francesco Bonizzi Jul 14 '14 at 16:44
  • Mr. Skeet posted a nice answer to [pass c# struct by reference?](http://stackoverflow.com/a/16614732/2596334) you might find helpful. – Scott Solmer Jul 14 '14 at 16:48

1 Answers1

1

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.

gunr2171
  • 16,104
  • 25
  • 61
  • 88
  • In addition, this is not depending on whether `TouchCollection` is struct or class. `player_` doesn't have a reference to the variable `touch_` itself even if it is a class, so reassigning to `touch_` doesn't affect the value `player_` has. – Ripple Jul 14 '14 at 17:58