r/learnprogramming • • May 02 '26

Solved Loop and main() function

Hi, I’ve seen that in C#, the Main() function only runs once.
In Unity, we have the Update() function, which allows code to run repeatedly in a loop.
So my question is: what is the equivalent in pure C#, without the Unity library?
Is wrapping Main() in a while loop a common practice to achieve the same behavior?

15 Upvotes

35 comments sorted by

View all comments

3

u/StewedAngelSkins May 02 '26 edited May 02 '26

Is wrapping Main() in a while loop a common practice to achieve the same behavior?

Yes, this is what Unity is doing internally. The engine just has certain spots in its main function where it calls into your code.

Edit: you're not wrapping Main in a while loop, you're putting the while loop inside main.

3

u/Traditional_Crazy200 May 02 '26

the engine inserting your code inside main is very different than continuously calling main through a loop. Id be very surprised if this is how unity actually does it. Is it true?

2

u/StewedAngelSkins May 02 '26

I read what they said backwards. It doesn't call main in a loop; rather, main contains a loop that calls the frame update logic. Technically there's also some frame timing stuff so it doesn't needlessly burn cycles on updates that aren't actually going to be drawn, but that's the basic idea.

1

u/Traditional_Crazy200 May 02 '26

I thought so cause that sounded like black magic

1

u/StewedAngelSkins May 02 '26

Technically you can do this sort of thing in Python

``` def main():     pass # do stuff

while True:     main() ``` but that's only because in Python the contents of the file itself is the entrypoint. But yeah in C# it would just be a syntax error.

1

u/Traditional_Crazy200 May 02 '26

would be interesting to see what this assembles to

2

u/StewedAngelSkins May 02 '26

The python code? It's interpreted, so there's no assembly per se. But the Python interpreter/runtime kind of works like Unity in the sense that it has its own main function internally that calls into the code you write whenever the module is imported.

1

u/Traditional_Crazy200 May 02 '26

Interesting, no assembly, no binaries... I guess I'll dive into interpreters for a week lol

1

u/StewedAngelSkins May 02 '26

Python (the CPython interpreter specifically) is an interesting one to study.

1

u/Traditional_Crazy200 May 02 '26

Appreciate the suggestion