its probably a noob question, but what is the advantage of local variables?
Offline
I find it useful for keeping track of enemy statistics; such as whether the enemy is visible or not. If you look at the enemy sprites in my Guardian 3D game, you will see extensive use of local variables for speed, agression, agility, status, etc. By using local variables, each enemy can have it's own "personality".
Offline
I like the_guardian's excellent explanation about local variables allowing each sprite in a set of similar ones to have its own "personality"!
Another benefit is, that local variables are restricted in namespace only to other local variables of the same sprite (and in future versions of Scratch possibly to global variables as well). That means you can duplicate a working sprite (like an "enemy") without each of the clones sharing the same internal state, as it were if you would use global variables.
The biggest difference between global and local variables is, that local variables can be manipulated (set/changed) only by the sprite they were created for. Other sprites may "read" their value (using the variable-sensor block), but cannot change them.
Offline
Even if you have 10 enemy space ship sprites, and you want them all to behave in the same way, it's much better to code them using local variables rather than global variables wherever possible:
You create 1 enemy, with global vars 'status 1' etc etc and duplicate it a further 9 times.
If you've used global vars for everything, you then need to go into each, remove all the references to the 'status 1', create a global 'status 2' and insert that into the scripts... and do it for each sprite. It's a tedious job!
If you used local vars then you've got nothing to do!
You may need to do some clever(er) coding though... as you can't change local variables remotely (you can only inspect them using that sensor block) you may have to broadcast to specific sprites to tel them to change values.
This in turn may lead to timing problems (I think there's a slight lag using broadcasts) so you may need to use global vars after all... just try hard to use them only when absoulutely necessary!
Last edited by SonicPopsDad (2008-08-18 05:47:52)
Offline