is it possible to call a function by a string (commonly found in game as a console).
for example, if someone types a word into a text box (like Restart) and the code would be able to run a function with the same name (like function Restart ).
is it possible to call a function by a string (commonly found in game as a console).
for example, if someone types a word into a text box (like Restart) and the code would be able to run a function with the same name (like function Restart ).
Sure, you can use reflection to get to the methods of any given class. Look at this article:
Specifically, scroll down to the Examples section with the MagicClass example. It tells you specifically what to do to get to call methods, when all you have is the name of the method in string form at runtime.
Reflection might be a little overkill for you, though. Unless you’re careful to restrict its use from an in-game console, the user could potentially call any method that’s a member of the class, if he knows what the name of the method is, not just those you’d like to expose for console use.
It might be a simpler and safer approach to simply switch over the strings and call the associated function like this:
public void ConsoleCallMethod(string methodNameFromConsole)
{
switch (methodNameFromConsole)
{
case "MethodA":
MethodA();
break;
case "MethodB":
MethodB();
break;
case "MethodC":
MethodC();
break;
default:
Debug.Log("Console doesn't support that");
break;
}
}
private void MethodA()
{
}
private void MethodB()
{
}
private void MethodC()
{
}
You could use Reflection for that purpose, google for it.
It is all ok now, i just used start coroutine, works a treat and, its in JS