Hi, I just started to use delegates, great stuff, works as expected. I just got this idea that I would like to assign a method to a delegate using a string with the methods name, but with no success. (Tried with Invoke, but didn’t work) Couldn’t really find anything on the forum about it either, but maybe I just don’t know what to search on. Any ideas anyone? PS. The method also takes one parameter, if that matters.
Pseudo code:
delegate void MyDelegate (int nr);
MyDelegate myDelegate;
string myString = MyMethod; //Same name as method..
void Start () {
myDelegate = myString; //I understand this won't work, but I hope you get the idea.
}
void MyMethod (int nr){
//Doing stuff..
}
There’s some roundabout ways of achieving what you want, but they’re slow and prone to error. If you explain the use case, I’m pretty sure that there’s better solutions than string-to-method.
The only way to do this is using System.Reflection, and you only ever want to use Reflection if you really, really have to. (It’s slow, it doesn’t work on all platforms, and it’s a pain.)
Are you doing this so that you can assign a function in the object’s Inspector view? Check out the UnityEvent class, it’s intended for exactly this purpose.
Thanks for your quick answers. (And for code tags ) Well, I just thought it would be handy for prototyping to pass a string from wherever (Yes, for instance from the inspector) and have my methods fireing up. But yes, I might just have to rethink now, seeing it wasn’t that easy…
If you want to assign a function to call from the inspector, set up a public UnityEvent, and use it’s Invoke method. The UnityEvent is what’s used for eg. Buttons. It lets you drag in any GameObject, and select a method from any component on that object, as long as that method has 0 or 1 argument that Unity knows how to draw - so a number, a string, or something that derives from UnityEngine.Object (most things).