I don't understand functions and start game

can you explain it in the most simplest way you can

Hi Mark,

In which course are you? Could you share the relevant code you would like to have explained?

Does Sean’s explanation in this thread help?

And mine in this?

In Start(), we call StartGame(). In StartGame(), we set the initial values for our variables so we can play our game (again) with those values. Then we log a few messages into our console. And we increase the max value by 1 with max = max + 1; so the computer can “guess” the initial max value.


See also:

unity 2d course

A function is basically a block of code. Code can be variable assignments, other functions etc. (Ben is referring all these things as statements.)

Generally you write a function and “fill the body of it” to make it easier to repeat things.

Let’s assume the following.

You want to print 2 things to the console.

print("Hello world.");
print("I am a game developer");

But what if want to do this in different places and want all print statements to be always the same.

You could repeat the code again and again and again…
OR

You write write a function.

void greet(){
  print("Hello world");
  print("I'm a game developer");
}

Now. Everytime you want to print this greeting to the console you just need to write:

greet();

This means that you execute the greet function. And this function executes both print statements. Btw. print is also a function…

Hope that helps a little bit?

so start game holds our code and start game allows me to restart the game when the game ends

im in the unity 2d game dev course

Kind of.

If you invoke a function it executes everything inside its body (everything between { and }).

That does not necessarily have to restart the game.

Maybe you can show me your specific function (please format it as code). And maybe I can explain it for your exact use case.

so a function allows me to reuse the code in it again and again

Yes.

It also allows you to structure your code a bit and keep it clean…

OK thanks i think i get it now

1 Like

If anything is unclear or needs more explanation, just let us know :wink:

also can can start game function be used used to restart a game once it has ended

I haven’t done the 2d course yet. So I can only explain in general.

Can you show us the code? Then I can maybe tell you whether it will restart the game…

Besides that: just try it. “Make mistakes as you will learn the most out of them” as Ben and Rick are always saying.

ok

thanks for the help

I’m glad @Naxos84 was able to clear this up you. :slight_smile:


See also:

@Mark_Fillebrown if one of the answers helped you. Then you could please mark it as a solution.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms