- Home /
Loop problem
Script 1
public void ActivateScript1(){
for (int i = 0; i < max; i++)
{
Script2.ActivateScript2();
Debug.Log("A");
}
}
Script 2
public void ActivateScript2(){
foreach (var item in collection)
{
Debug.Log("B");
}
}
ActivateScript1() is tied to a button.
If I press the button two times the console shows: A (2) B (4)
If I press the button three times the console shows: A (3) B (9)
Could someone explain what is happening and how I can get it so that the console shows: A (3) B (3)
Answer by Skrimel · Feb 23, 2021 at 09:36 AM
You call function, that iterates over "collection", from loop with "max" iterations. Each call of "ActivateScript2()" initiates iteration over "collection", which consists of 3 elements, as I can see from your logs. In "ActivateScript1()" you call "ActivateScript2()" in loop, as a result call of first function, calls second function "max" times.
As I understood, you need something like:
public void ActivateScript1(){
for (int i = 0; i < max; i++)
Debug.Log("A");
ActivateScript2();
}
public void ActivateScript2()
{
foreach (var item in collection)
Debug.Log("B");
}
Your answer
Follow this Question
Related Questions
Instantiate for loop skips some objects 1 Answer
Get child position from last gameobject in array 2 Answers
Why letters appear in reversed order ? ,Letters appear in reversed order 2 Answers
For loop update variables value before functions complete 2 Answers
How to set a value for each level without using a switch statement 2 Answers