Probably just some dumb minor mistake that I'm too stupid to see right now, but it really bothers me. I have this little game I'm working on in Unity and I wrote a method that is basically supposed to start the next level:
public void ButtonNextLevel()
{
string currentScene = Convert.ToString(SceneManager.GetActiveScene().name);
char[] currentSceneChars = new char[currentScene.Length];
int stringLength = currentScene.Length;
int levelIndex;
using (StringReader sr = new StringReader(currentScene))
{
sr.Read(currentSceneChars, 0, currentScene.Length - 2);
}
string levelIdentifier = new string(currentSceneChars);
Debug.Log(levelIdentifier);
if(levelIdentifier == "Level")
{
levelIndex = currentScene[stringLength - 1];
Debug.Log(levelIndex);
string nextSceneName = "Level " (levelIndex 1).ToString();
if(SceneManager.GetSceneByName(nextSceneName).IsValid())
{
SceneManager.LoadScene(nextSceneName);
}
else {GameWon();}
}
}
public void GameWon()
{
SceneManager.LoadScene("GameWon");
}
The main Problem seems to be the if(levelIdentifier == "Level")
statement. If I get to the point where this script is executed, I do get a response from Debug.Log(levelIdentifier);
(which clearly states "Level"
), but not from Debug.Log(levelIndex);
:
Debug Log
I don't understand why the if-statement isn't executed even though the requirements are met.
CodePudding user response:
I do get a response from Debug.Log(levelIdentifier); (which clearly states "Level")
Are you sure that there is no whitespace characters in the debug output (like space or something)? Try adding Debug.Log(levelIdentifier.Length);
also.
As for if
statement it seems like a very convoluted way to check if string starts with some prefix. Since Scene.name
is already a string
try using stringStartsWith
(another potentially useful one is string.Contains
):
var sceneName = SceneManager.GetActiveScene().name;
if(sceneName.StartsWith("Level"))
{
...
}
CodePudding user response:
In your levelIdentifier there are 2 null chars (\0) always will append. so levelIdentifier has has 2 '\0' chars in the end. that is why if statement fails
that is because you initialize char[] currentSceneChars = new char[currentScene.Length];
with full length of input string but not used last 2 slots of the char array. so those 2 chars kept as null