我们可以在Unity中轻松制作一个回调方法:
private void SimpleCallbak(Action<bool> onTaskReady ) {
// do something...
onTaskReady(true);
}
当 HandleInterstitialLoaded 事件处理程序触发时,如何触发回调 onAdReady :
private void RequestInterstitialWithCallbak(Action<bool> onAdReady ) {
interstitial = new InterstitialAd("ca-app-pub-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
interstitial.OnAdLoaded += HandleInterstitialLoaded;
interstitial.LoadAd(new AdRequest.Builder().Build());
onAdReady(true); //???????????
}
public void HandleInterstitialLoaded(object sender, EventArgs args) {
Debug.Log("HandleInterstitialLoaded event received.");
onAdReady(true); //???????????
}
答案 0 :(得分:2)
对代码进行简单修改,用lambda替换回调方法:
private void RequestInterstitialWithCallbak(Action<bool> onAdReady ) {
interstitial = new InterstitialAd("ca-app-pub-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
interstitial.OnAdLoaded += (sender, args) => {
Debug.Log("HandleInterstitialLoaded event received.");
onAdReady(true);
};
interstitial.LoadAd(new AdRequest.Builder().Build());
}
此处sender
和args
使用类型推断,允许我们通过省略类型说明符来缩短代码
有关使用lambdas进行回调的更多信息,请阅读Delegates and lambdas和Lambda Expressions上的官方文档
答案 1 :(得分:1)
我想你急于得到答案,这是基于UnholySheep的评论:
private Action<bool> _onAdReady;
private void RequestInterstitialWithCallbak(Action<bool> onAdReady)
{
_onAdReady = onAdReady;
interstitial = new InterstitialAd("ca-app-pub-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
interstitial.OnAdLoaded += HandleInterstitialLoaded;
interstitial.LoadAd(new AdRequest.Builder().Build());
_onAdReady?.Invoke(true); //???????????
}
public void HandleInterstitialLoaded(object sender, EventArgs args)
{
Debug.Log("HandleInterstitialLoaded event received.");
_onAdReady?.Invoke(true); //???????????
}