- Home /
Delegates and class constructors
I seem to not be able to figure delegates out. I need to use a delegate as parameter for a class constructor, to be able to access the constructor anytime directly from the class.
What I have:
public class Cheat{
public string cheat;
public Cheat(string cht){
cheat = cht;
}
}
What I want to do with this:
Cheat cheat = new Cheat("cheat", FUNCTION/DELEGATE);
Then I want to be able to use the thing like this:
cheat.assignedDelegate();
Answer by robhuhn · Sep 03, 2013 at 07:37 AM
This site explains how delegates work: http://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx
So basically you create a delegate
public delegate void CheatDelegate();
The delegate here is of type CheatDelegate
private CheatDelegate myDelegate;
This type can be treated like any other type e.g. to pass it to a constructor
public Cheat (CheatDelegate d)
{
this.myDelegate = d;
myDelegate();
}
And finally create the object and pass an anonymous delegate
new Cheat( delegate()
{
Debug.Log("my delegate");
});
Or a named method
new Cheat(new CheatDelegate(MyMethod));
...
void MyMethod()
{
Debug.Log("delegate from a named method");
}
When you get fed up with having to explicitly declare your delegates (i.e. type public delegate void funcName();
and then make one) for just another private delegate, you can start using System.Action or System.Func. You can have up to 16 parameters and the return value for Func for those delegates.
Still, sometimes it's just a good idea for clarity and readability reasons to declare your own delegates.
To illustrate: the first two lines of code can be compressed into
private System.Action myDelegate;
And the third line would be
public Cheat (System.Action d)
I thought Func is .net 3.5 and unity supports a .net 2.0 subset?
Good. $$anonymous$$ay be you want to mark it as an answer.