본문 바로가기

Unity

A method as a parameter - how to use Delegate

I was thinking about "would it be possible to use a method as a parameter?".

And actually, it was possible in JS but in C# it didn't work to pass a method right away.

So I found a way to do it in C# and it's called delegate.

Let's give it a try passing a method as a parameter.

example of delegate

As on the 8th line, declare a variable as a delegate. (delegateTestFunc)

The important thing to remember when you declare a delegate is you have to make sure it has the same parameter and return type as the method that you will make as a parameter.

As you can see from the picture above, the testFunc method has the same parameter and return type as the delegate method.

If you are done with declaring, create a method and a variable of the delegate.

You can use it as the 28th line, by using "new", you can pass the method as a parameter

or

Declaring delegateTestFunc

you can use it in "dTF = new" shape.

The reason to declare delegate TestFunc is because when I want to reference it from another script,

I had to declare it there to be able to use it.