List of Levels in Unity with C #

0

In the project where I work (with Unity 2017.3) I must use a single scene for all levels of the game. Each level has its class with its particular implementation, but they all inherit from the Level.cs class. What I need is to store the levels in such a way that what I save in a serialized file is only an index int to look for the script of the level where the player is left.

Base level:

public class Level
{
public int id;
public string name;

public Level()
{

}

public void ConfigureLevel(StageObject stage)
{
    //some stuff
}}

Here is a particular level:

public class Level_1: Level
{
int try= 0;

public Level_1(StageObject stage)
{
    base.id= 0;
    base.ConfigureLevel(stage);

}}

Here is the levelmanager that should be able to store the levels for then with the saved data instantiate the current level and not the first one:

public class LevelManager : Singleton<LevelManager>
{
Level currentLevel;
Stage stage1, stage2, stage3;
void Start()
{
//load saved data and player prefs
currentLevel = new Level1(stage1); // For now I am always loading level 1,but I want to load the last one visited (the saved level)
}
}
    
asked by Nogerad 03.04.2018 в 20:07
source

1 answer

0

You can add a script at runtime with the code: You just have to replace adding the script to load it by its name based on the saved level.

var scripts = Resources.LoadAll("Ubicación de script en carpeta resources", typeof(TextAsset)); 
foreach (TextAsset item in scripts) {//Agegamos los script al objeto que los debe contener, siempre será el main asset.
    gameObject.AddComponent (System.Type.GetType(item.name));
}

for example:

public class LevelManager : Singleton<LevelManager> {
   Level currentLevel;
   Stage stage1, stage2, stage3;
   void Start(){//load saved data and player prefs
      int savedLevel = PlayerPrefs.GetInt("LevelSaved");
      var script = Resources.Load("Scripts/Level_"+savedLevel, typeof(TextAsset));
      currentLevel = System.Activator.CreateInstance(System.Type.GetType(script)); // No estoy seguro que permita crear la instancia de la clase y aceptar parámetro, pero puedes checarlo....
      currentLevel.ConfigureLevel(stage1);//Tendrías que modificar el constructor y agregar el base.id en este método...  
   }
}
    
answered by 19.04.2018 в 20:14