Question about a 4 loop, please..

Hey, I’m trying to get a value per each item within a list (with multiple properties). ‘e.hours’ should each, individually per item in the list, be multiplied by ‘GetHourlyRate’. When I format it like I think it should be done, as in the last example, it is only writing the total for the last field instead of for each of them.

I can pretty much confirm that the GetHourlyRate function is working fine, as well as the ‘hours’ property, so that shouldn’t be an issue. I’ve played around with the debug location with no luck. I’ll eventually get the results out of the function, otherwise I’d be fine with one of the other ways. But for asking the question I wanted to keep the issue isolated to why I can’t get a variable assigned to the individual totals (I can hopefully take it from after that point) and I’m just wondering what is out of place or what step I am missing.

Thanks!

 public float CalculatePayEach()
        {//This Works.
            foreach (Employees e in fields)
          
            Debug.Log(e.hours * GetHourlyRate());
        }
        return payEach;
 public float CalculatePayEach()
        {//And this works.
            float x =1;
            foreach (Employees e in fields)
          
            Debug.Log(x * e.hours * GetHourlyRate());

            // myListChild.transform.position = Vector3.one
        }
        return payEach;
  public float CalculatePayEach()
{//This only prints one, the last, item.

      float x = 1;
            foreach (Employees e in fields)
                x = e.hours * GetHourlyRate();
          
            Debug.Log(x);
}
return payeach;

That will be because your Debug.Log is not inside the foreach loop. If you do not specify { and } for the start and end of a block of code like a loop or an if statement, then only the next single line will actually be in that block of code.

Basically this:

foreach (Employees e in fields)
    x = e.hours * GetHourlyRate();

    Debug.Log(x);

is the same as doing this:

foreach (Employees e in fields)
{
    x = e.hours * GetHourlyRate();
}

    Debug.Log(x);

See that the Debug.Log is not in the foreach? So you would need to do this:

foreach (Employees e in fields)
{
    x = e.hours * GetHourlyRate();
    Debug.Log(x);
}
1 Like

Hey, thank you. That was it, and it solved the issue. I knew it had to have been something important but relatively simple.

In my original, that entire loop is in a block (including the foreach), and I thought that block, that contained the loop statement, was itself all-inclusive. But, I see now that it’s only a single line that is automatically recognized as part of the loop, otherwise you have to set a new block. It makes sense, and I really appreciate it