简体   繁体   English

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

[英]Create callback method from another Event Handler in C# Unity

We can easily make a callback method in Unity like this: 我们可以像这样在Unity中轻松地创建一个回调方法:

private void SimpleCallbak(Action<bool> onTaskReady ) {

        // do something...
        onTaskReady(true);
    }

How do fire the callback onAdReady when HandleInterstitialLoaded event handler fire: 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); //???????????
    }

A simple modification of your code, replacing the callback method with a lambda: 对代码的简单修改,用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());
}

Here sender and args use type inference, allowing us to shorten the code a little bit by omitting the type specifiers 在这里, senderargs使用类型推断,从而使我们可以通过省略类型说明符来稍微缩短代码

For more information on using lambdas for callbacks you can read the official documentation on Delegates and lambdas and Lambda Expressions 有关使用lambda进行回调的更多信息,您可以阅读有关Delegates和lambdasLambda表达式的官方文档。

I guess ur in rush to get an answer, this is based on UnholySheep' comment: 我猜你急于得到答案,这是基于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); //???????????
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM