question about delegates

i was reading about delegates, and think i get it why they are for, just want to know how you use it in your project. where do you instantiate delegate? can somebody give a simpliest example of the use in unity? thank you!

unity answers cross post:Unity Discussions - A Space to Discuss All Things Unity

Enjoy

1- define a signature as a type:

public delegate void TestDelegate(string param);

2- declare

 TestDelegate myDelegate = myMethod;

myMethod signature must be equal as TestDelegate… so myMethod must looks like this

 myMethod (string param) {
code....
}

When you call myDelegate(hereTheParam), myMethod will be executed.

Example:
You need to open / close a door, depending on the way the character of your game took.
You could do the following:

public delegate void myDelegate(string param);
public TestDelegate MyDelegateDoor;


void OpenDoor(Door param) {
do something...
}

void CloseDoor(Door param) {
do something...
}


void manageDoor() {

if (direction = 1) MyDelegateDoor = OpenDoor;
else MyDelegateDoor = CloseDoor;

MyDelegateDoor(theDoor); //---> you will execute, in fact OpenDoor or CloseDoor
}

As well as Prime31’s excellent video that Paulo posted, there is a good example on the wiki.

It really helped show me how they could be used in a project, using delegates to drive a main menu gui. The cached version is here since the wiki is down atm.

Cached is a bit harder to read than it normally would be, but it’s simple, relevant and an interesting helpful technique.