- Home /
How to make a List or Array of functions with type Void
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
}
Im not completely sure, but i dont think a void function can be put in an array since it returns nothing, void means it returns no value.
You could make spawnRocks a List of ints, then use a switch/case statement on the random.range/index you chose to call different functions but that's not much different than your original method. Don't know enough program$$anonymous$$g to answer if you can put a function into List.
Answer by Niimus · Jan 11, 2015 at 05:52 AM
One solution here would be
// 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;
}
Delegate was what I was looking for. Thanks for the fast reply and simple answer.
Answer by Stardog · Jan 11, 2015 at 05:12 AM
This seems to contain a few solutions:
These two are also related and useful to know:
Answer by samf1111 · Dec 24, 2020 at 09:08 PM
you could make a list of MonoBehaviors and then make as much scripts as you want for each function and call them like myMonoBehaviors[0]();
.
Your answer
Follow this Question
Related Questions
What is the best way to instatiate an array of connected GameObjects? 0 Answers
C# Return Type Error? 1 Answer
How to call a function from another script in C# from array? 1 Answer
How to call a function with Vector3[] argument? 3 Answers
How to pass a Transform Array as an argument into a function in C#? 1 Answer