Create A Level Lock / Unlock System - Unity 4.6

We continue to explore the Unity 4.6 GUI system. In one of our previous posts, we learned about How to Create a Level Select Scroll Menu. In this post, we will use this foundation we have set, to build a Level Lock / Unlock System.

The Level Lock / Unlock System using Unity 4.6



If you have followed the Level Select Scroll Menu, you would have a scene named Level Select, of course you don't need to have the exact same Menu, in fact, any menu with some Level buttons would do. Make sure, you name the scene as World1, as we would be using this name in our code.
(In short, name the scene which has the Level Select Menu as World1.)

I hope you have a scene with a menu that somewhat looks like the one in the image below:


1. Import an image to indicate the Locked status of the levels. Either you can design it in photoshop, or search the internet. If you wanna follow along this post, then, download the image below and copy it into your project.


2. Once you import it, you got to change the image to being a Sprite type from Texture type. Click on the image in the Project panel and change the Texture Type to Sprite (2D and UI)



3. Now, duplicate the Level2 button by pressing ctrl+D. Rename it to LockedLevel2 (The name means a lot, as we would be using it in the code as well). Delete the Text component of the button. Add the Sprite you just added to this  Button's Image Source Image field. Change the alpha value to 255 so that we don't have a transparent sprite.
Also, change the Transition of the Button(Script) component to None as we don't want it to be clicked and neither we want to have any effects of it being clicked.


4. Repeat this to all the other Level buttons and name them accordingly, i.e., LockedLevel3 for Level3 and so on. Once you have done this you should have something like:


5. Create a new C# Script named LockLevel. Open it and add the below code to it.

using UnityEngine;
using System.Collections;

public class LockLevel : MonoBehaviour {
 
 
 public static int worlds = 1; //number of worlds
 public static int levels = 8; //number of levels
 
 private int worldIndex;   
 private int levelIndex;   
 
 
 void  Start (){
  PlayerPrefs.DeleteAll(); //erase data on start
  LockLevels();   //call function LockLevels
 }
 
 //function to lock the levels
 void  LockLevels (){
  //loop thorugh all the levels of all the worlds
  for (int i = 0; i < worlds; i++){
   for (int j = 1; j < levels; j++){
    worldIndex  = (i+1);
    levelIndex  = (j+1);
    //create a PlayerPrefs of that particular level and world and set it's to 0, if no key of that name exists
    if(!PlayerPrefs.HasKey("level"+worldIndex.ToString() +":" +levelIndex.ToString())){
     PlayerPrefs.SetInt("level"+worldIndex.ToString() +":" +levelIndex.ToString(),0);
    }
    
   }
  }
  
 }
}

In the above code, we simply set the PlayerPrefs of the Levels to 0. If it is the Level 1 of World 1, then we set the value of Level1:1 to 0.

6. Create a new C# script named LevelSelectScript and attach it to the Main Camera. Double click on the script to open it.

using UnityEngine;
using System.Collections;

public class LevelSelectScript : MonoBehaviour {

 private int worldIndex;   
 private int levelIndex;   

 void  Start (){
  //loop thorugh all the worlds
  for(int i = 1; i <= LockLevel.worlds; i++){
   if(Application.loadedLevelName == "World"+i){
    worldIndex = i;
    CheckLockedLevels(); 
   }
  }
 }

 //Level to load on button click. Will be used for Level button click event 
 public void Selectlevel(string worldLevel){
  Application.LoadLevel("Level"+worldLevel); //load the level
 }

 //uncomment the below code if you have a main menu scene to navigate to it on clicking escape when in World1 scene
 /*public void  Update (){
  if (Input.GetKeyDown(KeyCode.Escape) ){
   Application.LoadLevel("MainMenu");
  }   
 }*/
 
 //function to check for the levels locked
 void  CheckLockedLevels (){
  //loop through the levels of a particular world
  for(int j = 1; j < LockLevel.levels; j++){
   levelIndex = (j+1);
   if((PlayerPrefs.GetInt("level"+worldIndex.ToString() +":" +levelIndex.ToString()))==1){
    GameObject.Find("LockedLevel"+(j+1)).active = false;
    Debug.Log ("Unlocked");
   }
  }
 }
}

The above code checks which all levels are locked in a particular world. If a particular level is not locked we disable the LockedLevel buttons so that we can see the real Level buttons beneath them and click on them to start that particular level.Comment below if you have any questions about the script.

7. Now, add On Click event to the all the buttons. Add the Main Camera in the Object field and select the function Selectlevel in the Function field. This function expects a string parameter, type in 1.1 as this is a level 1 button of world 1


8. Repeat this to all the Level buttons and send their respective values. 1.2 for level2, 1.3 for level3 and so on.

9. Save the scene and create a new scene named Level1.1. Add a cube object, position it at (0, 0, 0). Rename it as Player. Add a Rigidbody component to it. Uncheck Use Gravity checkbox of the Rigidbody.

10. Add another cube and name it as Goal. Position it at (5, 0, 0). Check the Is Trigger checkbox.of the Collider component. 
Add a directional light if you need.

11. Create a new C# Script named PlayerMovement. Add this to the Player object. This scene is basically to demonstrate the working of the level unlocking system. Open the script and add the below code to it.

using UnityEngine;
using System.Collections;

public class PlayerMovement : MonoBehaviour {

 protected string currentLevel;
 protected int worldIndex;
 protected int levelIndex;
 // Use this for initialization
 void Start () {
  //save the current level name
  currentLevel = Application.loadedLevelName;
 }
 
 // Update is called once per frame
 void Update () {
  //move the player based on left and right arrow keys
  transform.Translate(Input.GetAxis("Horizontal")*Time.deltaTime*10f, 0, 0); //get input
 }

 //check if the player hits the Goal object
 void OnTriggerEnter(Collider other){
  if(other.gameObject.name=="Goal"){
   UnlockLevels();   //unlock next level funxtion 
  }
 }

 protected void  UnlockLevels (){
  //set the playerprefs value of next level to 1 to unlock
  for(int i = 0; i < LockLevel.worlds; i++){
   for(int j = 1; j < LockLevel.levels; j++){               
    if(currentLevel == "Level"+(i+1).ToString() +"." +j.ToString()){
     worldIndex  = (i+1);
     levelIndex  = (j+1);
     PlayerPrefs.SetInt("level"+worldIndex.ToString() +":" +levelIndex.ToString(),1);
    }
   }
  }
  //load the World1 level 
  Application.LoadLevel("World1");
 }
}

The code above gets input from keyboard to move the Player cube and moves it accordingly. Use the left and right arrow key to move the key and reach the Goal. Once the goal is reached the next level is unlocked. To verify this we load the Level Select scene i.e., World1 scene.

This is pretty much it. We have developed a Level lock / unlock system using the all new Unity 4.6 GUI and the classic C# scripting.

Note: 
- Name the level select menus as World1, World2 and so on.
- Name the game levels as Level1.1, Level1,2 for levels one and two of world one respectively.
-  If you have a Main Menu, attach the LockLevels script to the New Game button so that it deletes all the PlayerPrefs keys. - If you want to give the option of Continue, do not use this script as it deletes all the PlayerPrefs keys. 
- Make sure you add these levels in the Build Settings for them to switch scenes on click of a button.

See you around

Also check out,
Unity 4.6 GUI - Create A Dynamic Menu With The New UI
Unity 4.6 GUI - Create A Health Bar HUD
Unity 4.6 GUI - Create A Level Select Scroll Menu
Unity 4.6 GUI - Create An Animated Menu
Unity 4.6 GUI - Add Fade Between Scenes
Unity 4.6 GUI - Add A Loading Scene / Splash Screen
Unity 4.6 GUI - Create A Sliding Pause Menu
Unity 4.6 GUI - Create A Star Rating / Reward System
Share on Google+

About Sujit Horakeri

Sujit Horakeri is a game freak just like any other next door guy you would come across. He is a Web Developer by Profession, Game Developer by Choice.
Connect with him on:
    Blogger
    Facebook

55 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. thanks for the tutorial!
    but I have no idea when adding world1, world2, world3 to make it unlock/lockable.
    can you send me sample project for that? thanks!
    great tutorial anyway...

    ReplyDelete
  3. Great tutorial. I would like to see a 3 star rating system based on this logic. Can you make such a tutorial in order to have a more complete solution?

    thanks

    ReplyDelete
    Replies
    1. Thanks for stopping by and commenting.... we will surely make one soon...

      Delete
    2. Great I can't wait for it and it will be necessary for the lock unlock levels tutorial , i hope we have it soon :)

      Delete
    3. We'l bel posting the tutorial soon, meanwhile you can check the NEXT POST - TEASER located on the right sidebar...

      Delete
  4. Thank you ! Works perfectly !

    ReplyDelete
    Replies
    1. Glad you liked it :) Keep visiting...

      Delete
    2. Thank you ! works perfectly ! but,, the thing is after i debug this. and debug it again.. the next button is already unlocked. How can we reset it BRO? tnx in advance

      Delete
  5. What about the star reward tutorial? i thought it was going to be up last week :)

    ReplyDelete
    Replies
    1. Hi...The post on star rating system is out..check it out at
      http://www.thegamecontriver.com/2014/10/create-star-rating-reward-system-unity.html

      Delete
    2. That's great! Thank you so much! one question about extending functionality, how can I create 2 buttons in World1 scene, which according to from which level i enter into World1 scene, would sent me to this level again, and to the next level. For example " I go to World1 from level 5, and i want to go to level 5 by Retry button, and go to level6 by Next Level.
      Thank you in advance!

      Delete
    3. Cause I dont want to create world1 scene for every level)

      Delete
  6. This comment has been removed by the author.

    ReplyDelete
  7. How to create mobile Input:
    public void Update (){
    if (Input.GetKeyDown(KeyCode.Escape) ){
    Application.LoadLevel("MainMenu");
    }
    }

    ReplyDelete
  8. Hello Sir, I have a question... how can I lock again the unlocked levels when I build it or run it? Thanks! This was a wonderful tutorial. :)

    ReplyDelete
    Replies
    1. this is also my problem. hope Sujit Horakeri helps

      Delete
    2. Well, there is a LockLevel script which does this. As you have not attached this to any game object, it is not involved in the game when you build it. Maybe you can attach it to the MainCamera or something else in the very first level so as to lock the levels. Of course, you don't want to lock the levels every time this level is come across. Maybe you want to turn off the component/script when not required.
      Hope this makes sense.

      Delete
  9. Erorr building to mobile platform.
    Scripts/LevelSelectScript.cs(40,70): warning CS0618: `UnityEngine.GameObject.active' is obsolete: `GameObject.active is obsolete. Use GameObject.SetActive(), GameObject.activeSelf or GameObject.activeInHierarchy.'

    Can you help me, how to resolve this issue?
    thanks

    ReplyDelete
    Replies
    1. i also have this but the program works, but then i debuf it again the previous button are already unlocked. :(

      Delete
    2. Well.. I'm not sure how your scenes are setup. Say, I have a Main Menu scene from where I move to the World1 scene. This Main Menu has a main camera which has LockLevel script attached but is not active. And I have two buttons say New Game n Continue Game.

      Now, if I press the Continue Game button the LockLevel script should remain in disabled state.

      If I press the New Game button, make the script active before you move on to the next scene. Once this is done, the levels should be locked except the first one.

      Delete
  10. This comment has been removed by the author.

    ReplyDelete
  11. What would be the best way to record the best time and output it to a UI text on the level select?

    ReplyDelete
  12. Hello! Thank you a lot for all your tutorials :) I'm a begginer on Unity, i do this tuto but i want to add a button in my "MainMenu" scene to load the higher unlocked level, how i can do this please ?

    ReplyDelete
  13. In the note you say "If you want to give the option of Continue, do not use this script as it deletes all the PlayerPrefs keys."
    How can I modify this script to work without deleting all the PlayerPrefs keys and also provide the option of continue?...
    Also would the deletion of PlayerPref create problems with in game saved checkpoints?

    ReplyDelete
  14. Is there any video tutorial? Or please explain to me further because I'm really confused where should I name the level1.1 and World1.

    Please Help me. Thank you! I really Appreciate!

    I really need this to my thesis.

    Please be considerate because I'm a newbie. :)

    ReplyDelete
  15. Hello Mr. Sujit thank you for this tutorial , it helps me a lot but i have a problem regarding on locking levels . Once I unlock a level it cant be locked again .how can i fix this? .

    ReplyDelete
  16. Hi, thank you for this tutorial. I seem to be running into an issue of the lock button not disappearing. There are no errors, it runs smoothly but when I finish a level, it won't remove the lock pad image to reveal the next level button. If you could please help that would be great :)

    ReplyDelete
  17. i cant understand what i can take as a world1 and level1.1
    plz tell me the simple way bcz i am new to unity
    answer me with level 1 level2 etc

    ReplyDelete
  18. I have error about "GameObject.Find("LockedLevel"+(j+1)).active = false;"

    ReplyDelete
  19. Hi there!I did everything you wrote in this tutorial and it worked at first but then when i went back from level1.1 to World1 things got messed up.Is there a way you could help me?Like can i send you an e-mail describing what changed when i loaded the World1 scene again and also send you a copy of my project?If you have time of course otherwise i just need help fixing all these broken from the scripts(probably) things!Thanks!

    ReplyDelete
  20. Coding is Ok. Could you please upload source files with unity scene file...
    Most usefull for alll ...kindly upload the source also...

    ReplyDelete
  21. Can you share me this project new gui i have found ... email nvt2593@live.com

    ReplyDelete
  22. I found GameObject.Find("LockedLevel" + (j + 1)).active = false;

    ReplyDelete
  23. Hi, can you help me how to reset playerprefs value to null in order to play again the level 1 when you try to run it many times, because when you try it twice the value from the first try still there, I use Playerprefs.DeleteAll(); but the zero star still appear and its so annoying...
    Thank you.
    hope you'll help me,

    ReplyDelete
  24. It worked. Thank you for the tutorial. Great one!

    ReplyDelete
  25. what world1?
    I don't understand and I'm take world 1 error

    ReplyDelete
  26. Hello, thanks for toturiao it works fine
    How can i use more than 1 world ??

    ReplyDelete
  27. This Script is not working and it needed to be update very old please update the script to unity3d 5.3 the level is not unlocking for me

    ReplyDelete
  28. can you please post video for this?

    ReplyDelete
  29. It is not working on android.. after finishing 1st level.. 2nd level is still locked..

    ReplyDelete
  30. it does work for 1.1 to 1.8 level but 1.9 and so on is still lock.. how can i fix this...please help

    ReplyDelete
  31. sir my game is a quiz android app could i use your code of lock and unlock level???

    ReplyDelete
  32. thx man it works very well, even to reset the lock system its pretty easy.

    ReplyDelete
    Replies
    1. How did you reset the lock system?!

      Delete
    2. Hello brother can u please tell me what should i do ..Where i should put Worlds !! ...Can you send me simple project to my email earnads23@gmail.com

      Delete
  33. 7---- should i add camera on levelLocked buttons and give similar strings to them as respeect to their levels?

    ReplyDelete
  34. The introduction of keyless remotes has reduced the security concern of every vehicle owner.duplicate key maker near me

    ReplyDelete