Place to define variable

We’ve defined the variable speed “globally” in this lecture. Any specific reason why it was not defined within the function handling the movement? That seemed to be the logical place for me, unless it will be used in other functions in the future?

hi Hiner,

one thing that i can think of is that when you define a variable in a function, each time that function is called, that variable is created, used, then destroyed each iteration of the function.

so defining a variable once at the top of the script, keeps that variable for the lifetime of that script and can be used anywhere.

apart from that having it at the top of the script gives it a little more readability and bit more accessible for changing.

Darren

2 Likes

To expand on why it is good reason for this speed variable to be accessible by other functions:

Maybe your game needs to change the speed. A powerup that increases speed or an enemy attack that slows it down. If it’s not global (or accessible through some other component) then there’s no way for the movement function to know it’s changed.

2 Likes

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

Privacy & Terms