I’m trying to create a script that takes a random number and according to that number activates a function in a list or array. I can do this by doing a lot of conditional statements, however I was wondering if there was a simpler way of accomplishing the same task. I was thinking of
List<???> spawnRocks = new List<???>(); //Don't know which type I'm supposed to set it as so that it takes objects of type Void
spawnRocks.Add (spawnRocks1());
spawnRocks.Add (SpawnRockes2());
//confirmed working
void spawnRocks1() {
Instantiate something
}
void spawnRocks1() {
Instantiate something
}
// define a delegate type to match the required method signature
delegate void SpawnRocksMethod();
void CreateList()
{
// create a list of delegate objects as placeholders for the methods.
// note the methods must all be of type void with no parameters
// that is they must all have the same signature.
List<SpawnRocksMethod> spawnRocks = new List<SpawnRocksMethod>();
spawnRocks.Add(spawnRocks1);
spawnRocks.Add(spawnRocks2);
// call a method ...
spawnRocks[0]();
}
//confirmed working
void spawnRocks1()
{
Instantiate something;
}
void spawnRocks2()
{
Instantiate something;
}
as the accepted answer says, delegates would be the best way in this situation, because you know the return type. If you need a collection of methods with different return types, you would use an Action, which acts as a generic delegate.