I have a level in which every time the character interacts with an object starts the level all over again, with all its scripts.
But I want that every time the level is restarted the character goes faster.
But how can I increment the velocity value if every time the level is restarted, the script is also and the velocity variable is assigned all over again?
There is some kind of increment that I can use that works for all scripts?
Something that would let me change this value permanently independently from the initial assignment in every script?
If I remember correctly not assigning it won’t do because a memory cell may already have something in it.
To save variables across scenes and to store variables that are needed by more than one script, I use static variables. They are preserved across scenes and easily accessible by all.
To be more particular, I have sort of a registry object I call Dispatch. So, in your case, you can save the number of plays, and increase them on scene load, and then do whatever you want with this value (such as calculate speed etc.).
// In your actual game object...
void Awake() {
Dispatch.plays++;
mySpeed = Dispatch.plays * 10;
}
// The Dispatch class...
public class Dispatch {
public static int plays = 0;
}
Another common pattern, is to simply place these static variables in any “manager” type of object you have. So for example, your LevelManager class can have a LevelManager.currentScore
static accessible to all, and your SoundManager can have a SoundManager.isMusicOn
static.