从C#Unity中的另一个事件处理程序创建回调方法

时间:2018-01-04 15:44:41

标签: c# unity3d

我们可以在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); //???????????
    }

2 个答案:

答案 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());
}

此处senderargs使用类型推断,允许我们通过省略类型说明符来缩短代码

有关使用lambdas进行回调的更多信息,请阅读Delegates and lambdasLambda 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); //???????????
}