Search code examples
xnaforeachdrawstring

Drawstring refuses to stay on screen (XNA)


been fighting with this problem for a good 3 hours now, and i figured it was finally time to ask some professionals.

My problem is that i want to make a scrollbar, and I've figured out that i want to make it by using two integers and then give every item in the list an ID, and then say that all the items that has an ID thats in between the two integers are going to be shown, and then afterwards make 2 buttons that will + or - the integers so you can "scroll" though the items.

So to realize this i decided to make dummy code, to see how i could work it out. And for most part its working, however i have the problem now, that it seems that my draw function is refreshing the screen constantly (Even though I've put in a bool to make sure it woulden), and by doing that it keeps erasing the numbers I'm listing on the screen.

Heres the code:

List<int> test = new List<int>() {1,2,3,4,5,6,7 };

        int low = 0;
        int high = 3;
        int count;
        bool isDone = false;

 public override void Draw(GameTime gameTime)
        {
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, null, null, null);

if (!isDone)
            {
                int posX = 20;
                foreach (int nr in test)
                {

                    if (count == high)
                    {
                        isDone = true;
                        break;

                    }
                    else
                    {
                        count++;
                    }
                    if (count >= low && count <= high)
                    {
                        posX += 20;
                        spriteBatch.DrawString(gameFont, nr.ToString(), new Vector2(posX, 20), Color.White);
                    }
                }
            }

 spriteBatch.End();

}

Hopefully some of you clever folks can eye the mistake I've been missing.

Thanks in advance

~Etarnalazure.


Solution

  • You never reset your counter. Therefore, the numbers will be only visible in the first frame. Add

    count = 0;
    

    before the for-loop.

    Furthermore, you might want to revise your structure. If you use a List<>, then every item already has its index. And you don't have to iterate over each and every item, if you use a for loop:

    for(int i = low; i <= high; ++i)
    {
        var currentItem = list[i];
    }