Why is this happening in my functions?

Hi,

I have these two functions below, and when I run my code Function1 is being called first, then Function1 calls Function2.

Function2 returns true all the time in the current test environment, and I would expect the numbers written by Debug.Log in this order: 1, 2, 3, 4, 5, 6, 7

However the order the numbers show in the console are like this: 1, 2, 3, 4, 5, 6, 4, 5, 7

Do you have any ideas why is this happening? Why can’t the if (Function2(x, y) == true) statement recognize that Function2 returned true after it has been called?

Thanks in advance.

bool Function1() {
        Debug.Log("1");
        for (int x = 0; x <= (BoardManager.w - (int)rectTransform.sizeDelta.x); x++) {
            Debug.Log("2");
            for (int y = 0; y <= (BoardManager.h - (int)rectTransform.sizeDelta.y); y++) {
                Debug.Log("3");

                Function2(x, y);
                Debug.Log("6");

                if (Function2(x, y) == true) {
                    Debug.Log("7");
                    return true;
                }
            }
        }
        return false;
    }

bool Function2(int x, int y) {
        Debug.Log("4");

        for (int i = 0; i < childX.Count; i++) {
           
            if (BoardManager.cellStates[childX[i] + x, childY[i] + y] == 4) {
                Debug.Log("Function2 returned false");
                return false;
            }
        }
        Debug.Log("5");
        return true;
    }

That’s easy to explain. When you call a method and want to return something. The method will be ran THEN it will return the value. In this case you first run Debug.Log(4) and Debug.Log(5) then you return a boolean value after you’ve logged the 4 and 5. This is why the 7 will come after the 4 and 5.

Reply if you need further help.

Hi melle, thanks for the quick reply,

How could I make it run in the desired order then if I don’t want to jump back to 4, 5 before moving on to 7?

Thanks.

First of all, I can’t come up with any possible stiuations were you wanted that. If you tell something more about what you’re trying to achieve, I’ll be helping you out.

If you want a quick solution (not the most efficient), here you have it. Make Function3 without the Debug.Logs and use it when you only need to check the return value and you don’t want it to print out the 4 and 5.

The problem is not about the printing of numbers, those are just indicators on the working order of the script.

My problem is that I want to:

  • call Function2
  • wait for it to return
  • then check the result with the IF statement

And I want to run Function2 only once before checking the return value with the if statement, not twice.

Simply store the result of the first call to Function2 in a bool.

Perfect answer. Try following this.