Invoke/Call from String

I am working on a console command system that requires different commands and different calls for each instance, so my idea was to have a serialised class containing 2 strings, the alias (what will be typed in), and the call (line of code to run, like “CloseDoor()” for example).

But before I spend a while writing this all, I want to know if it is even possible to:

  1. Call a string like a normal function or line call
  2. Use arguments, like Type being the alias, using Type Name, and have the word Name used as an arg

Sorry if this isn’t too clear, but what I want to do in Unity is something like this:

alias: Open Door
call: OpenDoor()

so, if “Open Door D2” is typed, OpenDoor(D2) would be used.

An issue that would arise, is knowing whether that function or line call (like transform.position, for example) uses arguments or not, as that would cause pretty horrendous errors if you try to call OpenDoor(D2) when the function doesn’t take arguments, and others do.

Any ideas on how anything like this could be done?
I have a VERY closed system working at the moment, but it requires different versions of 2 scripts for every single instance that has different commands accessible.

this is definitely a situation where Reflection is in order.

You can use reflection to lookup the MethodInfo of something, determine the number of arguments, the types of the arguments, and what not.

Check out this class of mine where I use reflection heavily, it may help you familiarize yourself with it.

1 Like

In terms of parsing out arguments the easiest way would be to have a unique delimiter between the method name and the arguments so instead of Type Name or Open Door D2 you’d make the user do something like Type:Name or Open Door-D2. That way you can split the input on that unique delimiter and then use reflection to find a method with a name matching the left side value that takes the number of arguments included on the right side.

1 Like

Oh, and you’re probably going to want some easy conversion utils:

And a type lookup util: