Archive for the ‘ Tips/Advice ’ Category

C# Nullabalicious!

Something I’ve started using lately, and quite like… is C#’s ‘?’ property. This allows you to flag a parameter in a method’s constructor as ‘nullable’. In other words, when someone interfaces with your method, certain arguments can be left blank or set to null. This save’s creating overloaded methods. An example of such a method looks like:

public void PrintString(String text, int? numberOfTimes)
{
     int number = 1;
     if(numberOfTimes.HasValue)
          number = numberOfTimes.value;

     for(int i = 0; i < number + 1; i++)
     {
          DisplayString(text);
     }
}

Hope this helps or makes things easier in some cases :) .

How to detect a key press in XNA

XNA supplies us with a KeyboardState, that we can use to check whether a certain key has been pressed. But, it doesn’t check if that key is being held down. This can be a problem in some cases… For example, say we want to open a menu when the user presses the ‘escape’ key. If we just did the usual check of myKeyboardState.IsKeyDown(Keys.Escape) it would return true every iteration of your update function. This, would cause the menu to flash on/off multiple times and it gets annoying… fast. So, to fix this, create 2 private (or public) variables:

private KeyboardState keyboardState;
private KeyboardState lastKeyboardState;

In either your LoadContent() or Initialize() set

lastKeyboardState = Keyboard.GetState();

And at the top of your Update() function add

lastKeyboardState = keyboardState;
keyboardState = Keyboard.GetState();

Then, using a simple function

private bool HasKeyBeenPressed(Keys key)
{
     if(keyboardState.IsKeyDown(key) && lastKeyboardState.IsKeyUp(key)
     {
          return true;
     }
     else
     {
          return false;
     }
}

you can now check whether a key has been pressed, instead of just being held down! You can call it like so HasKeyBeenPressed(Keys.Escape);

Hope this helps!