[Solved] How did we get back 0 or 1?

So I’ve been having trouble understanding what’s going on in the UnlockLevel and IsLevelUnlocked methods, so I’ve been slowly going through the lecture again. It’s slowly making sense, but I’m stuck at a line in this code:

public static bool IsLevelUnlocked (int level){
	int levelValue = PlayerPrefs.GetInt (LEVEL_KEY + level.ToString ());
	bool isLevelUnlocked = (levelValue == 1);
if (level <= Application.levelCount - 1) {
	return isLevelUnlocked;
	} else {
		Debug.LogError ("Trying to query Level not in build order");
		return false; 


Specifically this:

	int levelValue = PlayerPrefs.GetInt (LEVEL_KEY + level.ToString ());

As I understand it, this is written to get the int of the current level back from the PlayerPrefs, which could be any number, but then Ben says “that gets back either 0, or nothing, or 1”. How is it just 0 or 1?

Also, am I right in thinking we write the next line to say that the bool only is true if the levelValue == 1?


Hey James!


You are right, the line you specified gets any whole number from the player prefs that is stored at the key. The reason it only returns a 0 or a 1, is that it returns whatever is stored there. In this case, when we are storing the unlock number, we use the following code inside of the UnlockLevel method:

PlayerPrefs.SetInt(LEVEL_KEY + level.ToString(), 1); // use 1 for true

This will always set it as 1.

That means when you lookup a number using PlayerPrefs.GetInt, you will either get 1 (the number you set inside of UnlockLevel, or 0 (not set). The reason 0 is returned when it isn’t set, is because 0 is the default value (docs).

levelValue == 1

Yes, the expression levelValue == 1 is a conditional, which always returns a boolean value. If the condition is met, it will return a true, otherwise it returns false.

Hopefully that helps!


Thanks @bendman! It’s a bit clearer now.

1 Like

Privacy & Terms