Frage

I have the following method that gets called when a gesture is match within my application but the counter only increments once within the method, so each additional match after the initial match doesn't increment the counter and label. Can someone see where if this is a flaw in my counter logic or if I should be implementing a counter differently?

This is my current solution which only increments on the first match:

void matcher_GestureMatch(Gesture gesture)
        {
            int scoreCntr = 0;
            lblGestureMatch.Content = gesture.Name;
            scoreCntr++;

            var soundEffects = Properties.Resources.punchSound;
            var player = new SoundPlayer(soundEffects);
            player.Load();
            player.Play();

            lblScoreCntr.Content = scoreCntr;

        }
War es hilfreich?

Lösung

You are resetting your count to 0 each time you run the method. Quickest fix is just declare the variable outside the method:

int scoreCntr = 0;
void matcher_GestureMatch(Gesture gesture)
{
    lblGestureMatch.Content = gesture.Name;
    scoreCntr++;

    var soundEffects = Properties.Resources.punchSound;
    var player = new SoundPlayer(soundEffects);
    player.Load();
    player.Play();

    lblScoreCntr.Content = scoreCntr;
}

Andere Tipps

You need to move scoreCntr out of scope of the method. It is only "alive" when that method runs, so you want to keep it alive during the lifetime of the class it is in. Here is an example of what it would look like:

    private int scoreCntr = 0;

    void matcher_GestureMatch(Gesture gesture)
    {
        lblGestureMatch.Content = gesture.Name;
        Interlocked.Increment(ref scoreCntr);

        var soundEffects = Properties.Resources.punchSound;
        var player = new SoundPlayer(soundEffects);
        player.Load();
        player.Play();

        lblScoreCntr.Content = scoreCntr;
    }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top