Obtaining level data dynamically using a variable

I’m storing level data in another script (“LevelData”) which gets loaded into a game manager script (“GameManager”) when required. More specifically, I’m calling on a function to change an array of values depending on the level selected by the user. These values are later used by GameManager.

When the user selects the level to play, it will toggle a variable (e.g. CurrentLevel).

I want to call the appropriate function (“DataLx” - where x is CurrentLevel) from the LevelScript, in the GameManager. I could just write a condition for each level possibility, but suspect there is a cleaner way to achieve this with the variable. Something like:

myLevelData.DataL[CurrentLevel] = new LevelData ();

CurrentLevel = 1;
myLevelData.DataL1 = new LevelData ();

CurrentLevel = 5;
myLevelData.DataL5 = new LevelData ();

...and so forth.
  1. What is the technical term for what I’m trying to achieve; and

  2. Is there a much better method to achieve this?

  3. Please provide an example based on the above!

Thank you!


This may have been asked/answered before, but being a newbie with C# I’m not exactly sure how to describe it!

Hi,

  1. I would say that you are trying to do a configuration of sorts

  2. First of all you can load the configurations from files (json for example),
    Instead of storing all levels as separate variables store them as an array, list or a different type of collection. Your description is a bit confusing but I think you are looking for a switch statement

    public void LoadLEvel(int levelNumber){

    switch(levelNUmber){
    case 1: InitializeLevel1(); break;
    case 2: InitializeLevel2(); break;

    }
    }

If you want to initialize all of the levels at start simply do a foreach

  1. example is in the code :slight_smile:

Hope this helps!