I want to select a random method from several methods. At first I tried to use lists, but I cannot find how you would write that. This is basically the code I have:
List list;
void Start()
{
list = new List</*method*/>();
}
void Button1()
{
var index = = Random.Next(list.Count);
/*method variable*/ = list[index];
}
I don’t need help with the random selection, just what would I use to put a method in a list. Thanks!
ps. if more information is needed, let me know.
You can first declare a method delegate type with its signature
public delegate void RandomlySelectableMethod();
Then simply use this type as a list generic argument.
list = new List<RandomlySelectableMethod>();
To call the method from the list, try
list[index]();
or
RandomlySelectableMethod method = list[index];
method();
You add delegates, not methods to the list. However, a delegate is created for you automatically if you assign a method.
void RandomMethod1()
{
// Random method stuff
}
list.Add(RandomMethod1);
I got it working using
delegate void methodGrabber();
List<methodGrabber> methods1;
void Start()
{
methods1 = new List<methodGrabber>();
methods1.Add(ProjectileSizeUp);
methods1.Add(ProjectileSpeedUp);
methods1.Add(ProjectileNumberUp);
method1();
}
for the list, and
void method1()
{
index1 = Random.Range(0, methods1.Count);
}
//and
public void ButtonFunc0()
{
methods1[index1]();
{
for choosing what method to use.
Generate a Random number and call the methods using a Switch statement.