Search code examples
c#loopsfor-loopwhile-loop

how to execute a line of code only once inside of a loop?


beginner here, I'm trying to do a while true loop that reads a value of an integer in a game indefinitely. what I wanna do is, when that integer = x value, execute a certain code but only once.

I used this code

while (true)
{

    
    var value = swed.ReadInt(localplayer, offsets.health);


    if (value == 70)
    {
        Console.WriteLine("hello");
    }


}

the problem is, when the value is 70, it prints "hello" forever when I only want it to be printed once. keep in mind I want that value to be read indefinitely and print "hello" once when its 70 so I can't use break otherwise it would only work once. I tried to use for loop which printed that message once as I wanted it to, but it only works if that value is 70 to begin with. it doesn't read that value continuously like the while loop. so I guess I need to use a nested loop? I tried a lot of different things bot nothing has worked so far


Solution

  • If you only want to print hello when the input value is 70 and not if the value doesn’t change but then again if it does change back to 70, then you could keep track of the previous value.

    var previousValue = 0;
    var currentValue = 0;
    
    while (true)
    {
      currentValue = swed.ReadInt(localPlayer, offsets.health);
    
      if (currentValue == 70 && previousValue != 70)
      {
        Console.WriteLine(“hello”);
      }
    
      previousValue = currentValue;
    }
    

    Not the most elegant of solutions but illustrates the basic idea. You can tidy up as required.