I have tried to figure out how to store several voids in a list and activating one of them depending on which level the player has reached.
I have searched how to setup a list of functions and it mentioned the “delegate void”. To be honest I have no idea what that is but it seem to work.
These are the variables I have:
delegate void levels();
public GameObject[] levelLayout;
public GameObject currentLevelLayout;
public int currentLevel;
First I fill the list with the level setup functions (this is run from the start function). The “LevelSetup_001” and 002 are functions:
Then when a new level is to be instantiated I need to find the corresponding level setup function. This is also where my problem lie. What should I write in the “foreach” to go through the function list?:
public void CreateLevel()
{
int tempInt = -1;
foreach (???? ???? in levelList)
{
tempInt += 1;
if (tempInt == currentLevel)
{
levelList[tempInt]();
}
}
}
Your list is a list of delegates. Delegates are basically just references to methods (functions).
when you do:
delegate void levels();
you are declaring a delegate named “levels” that can be assigned references to methods
that have the same signature. In this case, methods that don’t return anything (void) and don’t accept
any parameters. All of your levelSetup methods must have this signature, so your “LevelSetup_001”
must look like “void LevelSetup_001(){}” C# actually has a predefined delegate called an “Action” that is the same as your “levels” delegate.
Anyway, You would use the type you used when you declared the list, so probably “levels”
foreach (levels level in levelList)
{
tempInt += 1;
if (tempInt == currentLevel)
{
level();
}
}
However, it doesn’t look like you actually need a foreach statement here. You could replace your CreateLevel() method with:
public void CreateLevel()
{
levelList[currentLevel]();
}
I don’t see how you assign a value to “currentLevel” and I don’t know how much you know about list indexes, but you have to be careful. When you do this:
LevelSetup_001 will be at levelList[0] and levelList_002 will be at levelList[1].
So, If you are trying to setup level 1 and your currentLevel variable equals 1, you will
actually call LevelSetup_002.
I think I would use a dictionary of Action delegates here instead of a list, or even a switch statement if you aren’t going to have a lot of levels.