- Home /
How to make a callback function
Hi, i was wondering if someone could show or point me in the right direction of making my own delegate/callback function. Basically I want to make something that fires as a result of something, for instance if you have used the prime31 plug-ins (social networking ones in particular) they have delegates that fire once you have logged in or if you've failed to log in, hope i explained this well enough as im not the most experienced of programmers, any help would be greatly appreciated, thanks.
Answer by ABerlemont · Jun 18, 2014 at 10:09 AM
I found the answer of that question through those examples.
http://forum.unity3d.com/threads/another-noob-question-callback-functions-solved.27998/
http://msdn.microsoft.com/en-us/library/aa288459%28v=vs.71%29.aspx
public delegate void WhateverType(); // declare delegate type
protected WhateverType callbackFct; // to store the function
public void something(WhateverType myCallback){
callbackFct = myCallback;
}
void callProcess(){
something(dosomething);
}
void dosomething(){
//...
}
Another faster way to do the same thing would be to use the Action class from System
using System;
public Action myAction;
public Action<string> anotherAction;
void Start(){
myAction += callback;
anotherAction += callbackString;
myAction();
anotherAction("foo");
}
void callback(){ ... }
void callbackString(string aStringParam){ ... }
and you can subscribe multiple function to the same Action.
myAction += aCallback;
myAction += bCallback;
myAction(); // will call a and b
Answer by Ray-Pendergraph · Aug 11, 2011 at 07:13 PM
Have you tried Microsoft's delegate tutorial? That's pretty much all you need to know to start creating delegates. It has code samples, links to other resources and good explanation.
Answer by Alumi · May 11, 2018 at 02:39 AM
refer to this article: Link, using System.Action is the fastest way to implement callback function.
public IEnumerator FetchResponseFromWeb (System.Action<bool> callback) {
WWWForm form = new WWWForm();
WWW www = new WWW(url, form);
// ‘done’ will be null until the information has been fetched from the web or there is an error
yield return www;
// Make sure all code paths set the callback
if(www.error != null) {
callback(false);
} else {
print(www.text);
callback(true);
}
}
Start() {
StartCoroutine(FetchResponseFromWeb(callbackFunc);
}
public void callbackFunc(bool done) {
if(done != null) {
if(done)
print(“successfully fetched something from the web”);
else
print(“There was an error”);
}
}
Your answer
Follow this Question
Related Questions
Action delegate doesn't show in inspector. 1 Answer
Login form: Do I have to set custom delegates to null in OnDestroy? 0 Answers
Navmesh event on navigation end 0 Answers
How can callback from shared object 0 Answers
Delegate.Target null-check fails when it's actually null and also prints as null. 1 Answer