lachie whitehead
lachie whitehead

Reputation: 63

Action After Time with for loop

I have this for loop that scans every grid square for the values of neighboring squares and then sets a value in a grid when i press space:

public void GridScan(Vector3 worldposition, int range)
    {
        GetXY(worldposition, out int originx, out int originy);
        for (int x = 0; x < range; x++)
        {
            for (int y = 0; y < range; y++)
            {
                Debug.Log(GetValue(originx + x, originy + y));
                if ((GetValue(originx + x, originy + y)) == 100)
                {
                    if (Neighbours(GetWorldPosition(x, y), 2) < 2)
                    {
                        SetValue(x, y, 0);
                    }
                    if (Neighbours(GetWorldPosition(x, y), 2) > 3)
                    {
                        SetValue(x, y, 0);
                    }
                }

                if ((GetValue(originx + x, originy + y)) == 0)
                {
                    if (Neighbours(GetWorldPosition(x, y), 2) == 3)
                    {
                        SetValue(x, y, 100);
                    }
                }
            }

        }
    }

The problem is, the for loop would set the value before going on to the next grid square, meaning the count of neighbours with a certain value would be wrong (because some values would have changed).

Is there any way for me to set the value (The thing in the if statements) after a short period of time, and after the for loop is complete? I understand if i use Invoke, the loop will simply take the time to do the action inside the loop which is not what i want.

Upvotes: 0

Views: 48

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82474

I wouldn't go with a delay based solution on this, but with another loop to execute the SetValue calls once the loop that calculates all the values that needs to be set has finished.

Something like this might be a good start:

// Note: worldposition type is assumed to be a Position...
var newValues = new List<(Position WorldPosition, int Value)>();

foreach(var worldposition in worldpositionCollection)
{
    Debug.Log(GetValue(worldposition));
    if ((GetValue(worldposition)) == 100)
    {
        if (Neighbours(worldposition, 2) < 2)
        {
            newValues.Add((worldposition, 0));
        }
        if ((Neighbours(worldposition, 2)) > 3) 
        {
            newValues.Add((worldposition, 0));
        }
    }

    if ((GetValue(worldposition)) == 0)
    {
        if (Neighbours(worldposition, 2) == 3)
        {
            newValues.Add((worldposition, 100));
        }
    }
}
newValues.ForEach(val => SetValue(val.WorldPosition, val.Value));

Upvotes: 2

Related Questions