What is the use of FOR LOOP here?

What is the use of FOR LOOP here?

void Start()
{
for (int i = 0; i < comboButtons.Length; i++)
{
comboButtons[i].selectEntered.AddListener(OnComboButtonPressed);
}
}

The for loop is looping around a collection or array of buttons and assigning a listener to them.

So shouldn’t this code be under void Update() function instead of void Start()? As void Start() is played only once per code right?

No because update is called every frame and you only want to do this once.

I want this function to run every time I press a button interactable. So how will void Start() run every time I press a button?
Does this code mean that every time I press a button, the void Start() function is triggered. Then it loops through FOR Loop checking which button index was pressed. Then it calls the listener. Is this how it is?

The add listener binds to the button. You set it once and on clicking the button it triggers the event which runs the listeners. If you add in update, it will eventually crash the editor because you’ll be adding it 60 times every second until you run out of memory.

@Ninano as a follow-up, I’m getting the feeling that the nature of the questions you’re asking means you’ve never used C# or Unity before or are relatively new. The VR course is definitely not a beginners course and little or no explanation of the C# is given as you are expected to know these things. I would recommend taking the 2D and then 3D Unity courses first before attempting this course. These will give you a better understanding of C# and Unity as a whole and put you in a better place to follow this course.

Privacy & Terms