0
\$\begingroup\$

Is their a way to execute or call a random function in unity. Something like:-

  void Update(){random(func1(),func2())}

  void func1(){print("func1")} 

  void func2(){print("func2")}
\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

The solution by Qbix works when the list of possible functions is static. But what if the list is only known at runtime?

First you need to wrap the function calls into delegates, so you can treat them as variables. A premade delegate from the .NET framework which takes no arguments and returns no arguments is Action (There are also template delegates for functions with parameters and with return values). You can then add all the functions to a list and pick a random element from that list:

List<Action> functions = new List<Action>();
functions.Add( func1 );
functions.Add( func2 );
functions.Add( func3 );

Action randomFunc = functions[new Random().Next(0, functions.Count)];
randomFunc();
\$\endgroup\$
3
  • \$\begingroup\$ This is almost certainly the best option. Though I would say that you may want to deeply consider your reason for calling a random function as opposed to a function that has random output or effect inside the function itself. \$\endgroup\$ Jul 18, 2016 at 15:27
  • 1
    \$\begingroup\$ @JesseWilliams As I said: It's a useful pattern when the list of functions is not known at runtime. For example when you have various circumstances which define which random behaviors are possible and which are not. \$\endgroup\$
    – Philipp
    Jul 18, 2016 at 15:49
  • \$\begingroup\$ Oh for sure - that was more a tip to the OP. It's like GOTO - it still exists for a reason, and sometimes it's just the way to do something, but those times should really be evaluated for better options. :) \$\endgroup\$ Jul 18, 2016 at 15:56
0
\$\begingroup\$

Simplest way in the world:

Random random = new Random();
// it will roll from 0 (inclusive) to 2 (exclusive) so 0 and 1
int number = number.Next(0, 2);

if(number == 0) func1();
else if(number == 1) func2();
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Simpler still; remove if(number == 1). \$\endgroup\$
    – Droppy
    Jul 18, 2016 at 13:34

Not the answer you're looking for? Browse other questions tagged .