I have an enum defined like so:
public enum Direction
{
Left,
Right,
Up,
Down
}
And I the following variable in a class:
private Direction direction;
In the constructor, I assign the variable:
direction = Direction.Right;
Then, in a method in the same class, I try to assign a new Enum value:
direction = Direction.Down;
But it won't let me! It keeps going back to the Right value even thought the only place where it开发者_StackOverflow社区 gets set is in the constructor!
What's going on? o_O
EDIT - MORE CODE
namespace MyFirstGame
{
public enum Direction
{
Left,
Right,
Up,
Down
}
}
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace MyFirstGame
{
public class Invader : Sprite, IMovable
{
private InvaderType invaderType { get; set; }
private Direction direction;
private Vector2 speed;
public Invader(Texture2D image, Vector2 position)
: base(image, position, new Point(30, 16), new Point(0, 0), new Point(2, 0))
{
direction = Direction.Right;
speed.X += 30;
}
public override void Update(GameTime gameTime, Rectangle clientBounds)
{
timeSinceLastFrame += gameTime.ElapsedGameTime.Milliseconds;
if (timeSinceLastFrame > milliSecondsPerFrame)
{
timeSinceLastFrame -= milliSecondsPerFrame;
++currentFrame.X;
if (currentFrame.X >= SheetSize.X)
{
currentFrame.X = 0;
}
Move(direction, clientBounds);
}
}
public void Move(Direction direction, Rectangle clientBounds)
{
if (direction == Direction.Right)
{
//is invader 3 px from the right edge?
//if yes: then drop
//else keep on truckin' to the right!
if (position.X >= (clientBounds.Width - (Image.Width + 3)))
{
//position.X = 0;
position.Y += speed.X;
direction = Direction.Down;
}
else
{
position.X += speed.X; //Speed
}
}
else if (direction == Direction.Down)
{
speed.X *= -1;
position.X += speed.X;
}
}
}
}
The method
Assuming that you don't have stale binaries (as pointed out by Oded)...
Set a breakpoint on the assignment, and make sure that it actually executes. Then, immediately after the assignment (use Step Over
), verify the value of direction
.
If it's correct at that point, then something else is causing it to be reset.
Yes, I am answering my own question :-)
As for why it didn't work. I know for one part why and for the other I don't.
The part I know:
I had this method call in my Update() method:
Move(direction, clientBounds);
But the thing is that Enums are structs. The parameter in the Move(direction, clientBounds) method is actually being copied! Any changes that take place inside the method have no affect on the original value of the variable. So anytime I ended up with the original value when passing out of the Move() method.
The thing I can't rely place right now is the fact that I removed the direction as a parameter from the Move method call and I now assign a new direction directly to the class level variable private Direction direction;. This seems to work perfectly :-) But why?
精彩评论