1. First we need to construct a class for transmitting data and hosting the callback function
For example: (custom constructs as needed)
1 usingUnityengine;2 usingSystem.Collections;3 4 //callback function5 Public Delegate voidWarningresult ();6 Public classWarningmodel:monobehaviour7 {8 //callback function9 PublicWarningresult result;Ten //Warning Text One Public stringvalue; A - //construct a warning structure body - PublicWarningmodel (stringS_value, Warningresult S_result =NULL) the { - This. Value =S_value; - This. result =S_result; - } +}
2. Then instantiate it when needed to construct the structure
Like what:
1 /// <summary>2 ///Enter the game button trigger3 /// </summary>4 voidOnloginclick ()5 {6 //Verify your account password7 //If the account password is incorrect, display the warning panel and return8 if(M_inputaccount.text = =""|| M_inputpassword.text = ="")9 {Ten //warning Message//callback function OneWarningManager.instance.AddWarringError ("The account password entered is incorrect, please re-enter", Result); A return; - } - the - //Enter game, button deprecated -M_entergamebtn.interactable =false; - + - } + //callback function for testing A voidResult () at { -Debug.Log ("Login Interface callback function"); - } -
3. Finally take the callback function in the class that needs to implement the function, and implement the method
As follows:
1 //callback function after handling a warning2 PrivateWarningresult result;3 4 /// <summary>5 ///method for displaying warning messages for external calls to be passed6 /// </summary>7 /// <param name= "s_warning" >warning message structure body</param>8 Public voiddoshowwarring (Warningmodel s_warning)9 {Ten //activating the warning interface OneGameobject.setactive (true); A - //If the game object does not come and is found, first assign the game object - if(M_warningtex = =NULL) the { - Init (); - } - + //displaying warning messages -M_warningtex.text =S_warning.value; + //populating the callback function A This. result =S_warning.result; at - //if the callback function is not empty, the callback function is executed - if(Result! =NULL) - { - result (); - } in}
About the application of delegate and callback function in unity