randomize a function from a array (C#)

i have a A.I script with different functions for the conditions on which the enemy shall walk. I want to make a Invoke Repeating() on a function called RandomFunction(). This function shall do a random.range and select randomly from the array of functions, which are [5].

with invokerepeating repeating every 1 second a new function will be called and it should make the player walk randomly around every 1 second.

How would i go about making an array of functions in c#, and how can i use random.range in this array.

private System.Action myUpdate = ()=>{};
private System.Action actions = null;
void Start(){
actions = new System.Action {MethodA,MethodB, MethodC, MethodD, MethodE };
InvokeRepeating(“Randomizer”, 1.0f);
}

void Udpate()
{
   myUpdate();
}

void Randomizer(){
    int rand = Random.Range(0, actions.Length);
    myUpdate = actions[rand];
}

void MethodA(){ Debug.Log("A");}
void MethodB(){ Debug.Log("B");}
void MethodC(){ Debug.Log("C");}
void MethodD(){ Debug.Log("D");}
void MethodC(){ Debug.Log("E");}

myUpdate is a delegate, so pretty much a reference to a method. What is done in the declaration is just a fancy way to prevent null reference so a default method is added (you may print something to actually see that something is wrong).

The Update just calls that delegate so indirectly it is calling the method it is referring to. The Randomizer method just gets a random method out of an array of methods.

In case of, Action is just a short way for generic delegate.

You can store functions in an array using the Func<> type, eg:

Define an array of 5 functions (You can’t use void as the return type afaik, so bool will have to do)

Func<bool>[] AnimList = new Func<bool> [5];

Create multiple functions that return the desired type (in this case bool)

bool Idle() { Debug.Log("Idle"); return true; }
bool Yawn() { Debug.Log("Yawn"); return true; }

Assign the function’s to array indexes

AnimList[0] = Idle;
AnimList[1] = Yawn;

Then you can send the Random.Range int’s directly into the array index

AnimList[UnityEngine.Random.Range(0, AnimList.Length)]();

I don’t see why you want to put your functions in an array here - it’s probably possible to hack something together using delegate variables (not sure, never tried), but I think that’s overcomplicating things - instead, why not simply write a switch, something like

void ExecuteFuntionByIndex(int index){
 switch(index){
  case 0:
   FunctionZero();
   break;
 case 1: 
  FunctionOne();
  break;
 case 2:
  FunctionTwo();
  break;
 //..etc. for how many functins you have
 default:
  //Default to function 0 when you get an invalid index
  FunctionZero();
  break;
 }
}