I noted two more errors to rectify, which might be reflected in the course later on, but as for now the first is one is to check for any validations in the file name the user can specify:
public void NewGame()
{
string userInput = textField.text;
if (!string.IsNullOrEmpty(userInput))
{
userInput = System.Text.RegularExpressions.Regex.Replace(userInput, "[^a-zA-Z0-9_-]", "_");
savingWrapper.value.NewGame(userInput);
}
}
This line of code uses a regular expression to replace any character in the text field that is not a lowercase letter either uppercase or lowercase, a digit from zero to nine, an underscore, or a hyphen, with an underscore.
The angular hat at the beginning of the characters inside the square brackets is a negation symbol, so any characters that do not match the one we have specified, will simply be replaced with an underscore.
This is good practice to restrict certain characters in file names to ensure compatibility across different operating systems
Another is in the SavingSystem.cs
, where if in the worst case we have no value for the lastSceneBuildIndex
, we have previously simply loaded the current active scene with SceneManager.GetActiveScene().buildIndex
, which would reload the main menu scene.
To prevent this, you can define a default scene yourself:
[SerializeField] int defaultBuildIndex = 1;
public IEnumerator LoadLastScene(string saveFile)
{
Dictionary<string, object> state = LoadFile(saveFile);
int buildIndex = defaultBuildIndex;
if (state.ContainsKey("lastSceneBuildIndex"))
{
buildIndex = (int)state["lastSceneBuildIndex"];
}
// ...
}