[NOT URGENT] Perhaps a more efficient way to code playerprefs isUnlocked?

Just working on the playerpref code and noticed another way to write the code.

The code that was given in the video is as follows:

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 a level not in build order");
			return false;
		}
	}

This works well enough, but I thought it might slow things down, if seems to call a PlayerPrefs at the start even if the level is out of bounds, wouldnt it be better ti first check if the the level is within the levelCount first? As follows…

public static bool isLevelUnlocked(int level){

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

Hope thats useful (and correct).

Thanks

-Sat

1 Like

Thanks for sharing what seems like a perfectly good improvement

Privacy & Terms