Tuesday, September 1, 2009

XNA C# Gotcha #1

Thought I would post a problem I encountered and the solution I figured out.

Given:

A class, mySpriteClass, with method:

public Vector2 position { get; set; } // Sprite position on screen


And trying to update position in the game update loop with the following line:

mySprite1.position.X += 1;


Gives the error:
Cannot modify the return value of 'mySpriteClass.position' because it is not a variable


Change
mySprite1.position.X += 1;

to
Vector2 Position = new Vector2(mySprite1.position.X + 1, mySprite1.position.Y);
mySprite1.position = Position;


I thought I knew what is going on here, but when I tried to explain it, it got out of hand. Its something to do with value types vs. reference types.


No comments: