Now that the game is looking better, we can add some more content in to it. Luckily the jagged array we created earlier easily supports adding more levels. Levels can be any size, even with variable column heights per row. Double-click on the Sokoban
script in the Project panel and switch over to MonoDevelop. Find levels array
and modify it to be as follows:
// Create the top array, this will store the level arrays int[][][] levels = { // Create the level array, this will store the row array new int [][] { // Create all row array, these will store column data new int[] {1,1,1,1,1,1,1,1}, new int[] {1,0,0,1,0,0,0,1}, new int[] {1,0,3,3,0,3,0,1}, new int[] {1,0,0,1,0,1,0,1}, new int[] {1,0,0,1,3,1,0,1}, new int[] {1,0,0,2,2,2,2,1}, new int[] {1,0,0,1,0,4,1,1}, new int[] {1,1,1,1,1,1,1,1} }, // Create a new level new int [][] { new int[] {1,1,1,1,0,0,0,0}, new int[] {1,0,0,1,1,1,1,1}, new int[] {1,0,2,0,0,3,0,1}, new int[] {1,0,3,0,0,2,4,1}, new int[] {1,1,1,0,0,1,1,1}, new int[] {0,0,1,1,1,1,0,0} }, // Create a new level new int [][] { new int[] {1,1,1,1,1,1,1,1}, new int[] {1,4,0,1,2,2,2,1}, new int[] {1,0,0,3,3,0,0,1}, new int[] {1,0,3,0,0,0,1,1}, new int[] {1,0,0,1,1,1,1}, new int[] {1,0,0,1}, new int[] {1,1,1,1} } };
The preceding code has given us two extra levels, bringing the total to three. The layout of the arrays is still very visual and you can easily see the level layout just by looking at the arrays.
Our BuildLevel, CheckIfPlayerIsAttempingToMove and MovePlayer
methods only work on the first level at the moment, let's update them to always use the users current level. We'll have to store which level the player is currently on and use that level at all times, incrementing the value when a level is finished. As we'll want this value to persist between plays, we'll be using the PlayerPrefs
object that Unity provides for saving player data. Before we get the value, we need to check that it is actually set and exists; otherwise we could see some odd results.
Start by declaring our variable for use at the top of the Sokoban
script as follows:
int currentLevel;
Next, we'll need to get the value of the current level from the PlayerPrefs
object and store it in the Awake
method. Add the following code to the top of your Awake
method:
if (PlayerPrefs.HasKey("currentLevel")) { currentLevel = PlayerPrefs.GetInt("currentLevel"); } else { currentLevel = 0; PlayerPrefs.SetInt("currentLevel", currentLevel); }
Here we are checking if we have a value already stored in the PlayerPrefs
object, if we do then use it, if we don't then set currentLevel
to 0
, and then save it to the PlayerPrefs
object. To fix the methods mentioned earlier, click on Search | Replace. A new window will appear. Type levels[0]
in the top box and levels[currentLevel]
in the bottom one, and then click on All.
18.191.144.194