This might be a bit misplaced but is there a way to call a function by name in Unity?

I've tried Invoke(string, float) but that doesn't accept parameters. I've tried StartCoroutine but that requires a yield return new statement. I've also tried reflection, like this:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);

But this doesn't even compile giving an error of NullReferenceException: Object reference not set to an instance of an object and I don't really know why. Thanks for the help guys.

  • 1
    \$\begingroup\$ You'd have to tell us the errors you're seeing if you want to know why your reflection code isn't working. \$\endgroup\$ – MichaelHouse Aug 2 '17 at 20:11
  • \$\begingroup\$ @Byte56 Is this OK? I already stated what I've tried... what else do I need to put? \$\endgroup\$ – Daneolog Aug 2 '17 at 20:25
  • \$\begingroup\$ Have you looked up why programs return a null reference exception generally speaking? Then looked for that situation in your own code? You're trying to use some variable that hasn't been assigned to, or it's being assigned null. Attach the debugger and check it out. \$\endgroup\$ – MichaelHouse Aug 2 '17 at 20:27
  • \$\begingroup\$ Look... the point is that I copied the code exactly from the post, and it hasn't really worked. I checked my code thoroughly for the problem and there is no problem. The problem is with that particular statement. \$\endgroup\$ – Daneolog Aug 2 '17 at 20:43
  • 2
    \$\begingroup\$ Not all code found on the internet can just be pasted into your existing code and it'll work. As I said, you need to attach the debugger, find out where the problem is. Which variable is null? Why is it null? Did you look at the documentation? Did you know that GetMethod returns null if the method isn't found? Are you calling GetMethod on the right type? Are you searching for the right method? You haven't given us enough information to answer your question, so it remains closed. \$\endgroup\$ – MichaelHouse Aug 2 '17 at 20:50

Browse other questions tagged or ask your own question.