Skip to content

Tutorial: How to Create Level Management?

Hasan Bayat edited this page Sep 21, 2017 · 2 revisions

How to Save Levels?

In this tutorial we want to learn how to save levels progress.

Getting Started

  1. Download Save Game Free
  2. Create a new c# script called Level and put the below content in it:
public struct Level
{

	public bool completed;
	public bool unlocked;

}
  1. Create a new c# script called LevelManager and put the below content in it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using BayatGames.SaveGameFree;

public class LevelManager : MonoBehaviour
{

	private static LevelManager m_Singleton;

	public static LevelManager Singleton
	{
		get
		{
			return m_Singleton;
		}
	}

	protected Dictionary<int, Level> m_Levels;

	void Awake ()
	{
		if ( m_Singleton != null )
		{
			Destroy ( gameObject );
			return;
		}
		m_Singleton = this;
		m_Levels = new Dictionary<int, Level> ();

		// Adding default levels
		for ( int i = 0; i < 100; i++ )
		{
			m_Levels.Add ( i, new Level () );
		}
                Load ();
	}

	void OnApplicationQuit ()
	{
		Save ();
	}

	void Save ()
	{
		SaveGame.Save<Dictionary<int, Level>> ( "levels", m_Levels );
	}

	void Load ()
	{
		m_Levels = SaveGame.Load<Dictionary<int, Level>> ( "levels" );
	}

	public void SetLevelUnlocked ( int id, bool unlock )
	{
		if ( HasLevel ( id ) )
		{
			Level level = m_Levels [ id ];
			level.unlocked = unlock;
			m_Levels [ id ] = level;
		}
	}

	public void SetLevelCompleted ( int id, bool complete )
	{
		if ( HasLevel ( id ) )
		{
			Level level = m_Levels [ id ];
			level.completed = complete;
			m_Levels [ id ] = level;
		}
	}

	public Level GetLevel ( int id )
	{
		Level level;
		m_Levels.TryGetValue ( id, out level );
		return level;
	}

	public bool HasLevel ( int id )
	{
		return m_Levels.ContainsKey ( id );
	}

}
  1. Now you have a level management system, just call the SetLevelUnlocked, SetLevelCompleted methods from LevelManager to unlock and mark levels as completed.

License

MIT @ Bayat Games

Made with ❤️ Bayat Games

Clone this wiki locally