如何将 admob 广告加载到 unity 5 项目中?

How to load admob ads into a unity 5 project?

基本上我正在尝试将横幅广告加载到我的 Unity 5 项目中并导出到 iOS。

这是我在 unity 中调用的代码,它附加到一个游戏对象:

using UnityEngine;
using System.Collections;
using GoogleMobileAds.Api;
using System;

public class AdController : MonoBehaviour {

    InterstitialAd interstitial;
    BannerView bannerView;

    void Start () {

        //------ Banner Ad -------
        // Create a 320x50 banner at the top of the screen.
        // Put your Admob banner ad id here
        bannerView = new BannerView(
            "ca-app-pub-xxxxxxxxxxxxxxxx", AdSize.SmartBanner, AdPosition.Top);
        // Create ad request
        AdRequest request = new AdRequest.Builder().Build();
        // Load the banner with the request.
        bannerView.LoadAd(request);        
        bannerView.Show();

        //---- Interstitial Ad -----
        // Initialize an InterstitialAd.
        // Put your admob interstitial ad id here:
        interstitial = new InterstitialAd("ca-app-pub-xxxxxxxxxxxxxxx");

        //Add callback for when ad is loaded
        interstitial.AdLoaded += HandleAdLoaded;

        // Create an ad request.
        AdRequest requestInterstitial = new AdRequest.Builder().Build();
        // Load the interstitial with the request.
        interstitial.LoadAd(requestInterstitial);
    }



    public void HandleAdLoaded(object sender, EventArgs args) {

        interstitial.Show ();
    }


    void OnDestroy(){
        if (interstitial!=null) {
            interstitial.AdLoaded -= HandleAdLoaded;
            interstitial.Destroy ();
        }
        if(bannerView!=null){
            bannerView.Destroy ();
        }
    }

}

我正在使用:

有人有这个来投放广告吗?注意:我确实用正确的广告单元 ID 替换了 xxxxx。

  1. 向您的统一项目添加一些代码
    • 将此 c# class 添加到您的 Unity 项目中
    • 从您的项目
    • 的某处调用这个class的函数
  2. 尽早调用构造函数 "AD_AdsiOS" 并传递您的 AdMob 广告 ID
  3. 调用 "ShowInterstitialAd" 显示全屏广告
  4. 调用 "ShowBannerAdTopRight" 在右上角显示横幅广告
  5. 调用"HideBannerAds"隐藏横幅广告

#if UNITY_IPHONE
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
 
public class AD_AdsiOS
{
#if !UNITY_EDITOR
    [DllImport ("__Internal")]
    private static extern void _initAds(string p_adMobID);
    [DllImport ("__Internal")]
    private static extern void _showInterstitialAd();
    [DllImport ("__Internal")]
    private static extern void _showBannerAdTopRight();
    [DllImport ("__Internal")]
    private static extern void _hideBannerAds();
#endif
 
    public AD_AdsiOS(string p_adMobID)
    {
#if UNITY_EDITOR
        Debug.Log("AD_AdsiOS: will not work in editor.");
#else
        _initAds(p_adMobID);
#endif
    }
 
    public void ShowInterstitialAd()
    {
#if UNITY_EDITOR
        Debug.Log("AD_AdsiOS: ShowInterstitialAd called in editor.");
#else
        _showInterstitialAd();
#endif
    }
 
    public void ShowBannerAdTopRight()
    {
#if UNITY_EDITOR
        Debug.Log("AD_AdsiOS: ShowBannerAdTopRight called in editor.");
#else
        _showBannerAdTopRight();
#endif
    }
 
    public void HideBannerAds()
    {
#if UNITY_EDITOR
        Debug.Log("AD_AdsiOS: HideBannerAds called in editor.");
#else
        _hideBannerAds();
#endif
    }
}
#endif

  • 编译为Xcode
  • 第一步完成:)

    1. 管理 Xcode 中的库(来源:https://developers.google.com/mobile-ads-sdk/docs/
  • 下载 AdMob SDK
  • 在您的项目根文件夹中创建一个名为 "GoogleAdMobAdsSdkiOS"
  • 的新文件夹
  • 将下载的 SDK 中的所有文件(但不是 "Add-ons" 文件夹)复制到新的 "GoogleAdMobAdsSdkiOS"
  • 右键单击您的项目 ("Unity-iPhone"),然后按 "Add-Files to Unity iPhone" 和 select 项目根目录中的新 "GoogleAdMobAdsSdkiOS" 文件夹
  • 打开 Build Phases 选项卡下的 Link Binary With Libraries 下拉菜单。使用可见的 + 按钮从 iOS SDK 添加框架。将 SystemConfiguration、StoreKit、MessageUI、AVFoundation 和 AdSupport 添加到两个目标(检查故障排除步骤 1 和 2)
  • 您现在需要将 -ObjC 添加到 !THE PROJECT 的其他 Linker 标志中! (不是目标)
  • 第 2 步完成:D

    1. 添加一些代码(来源:https://developers.google.com/mobile-ads-sdk/docs/admob/fundamentals
  • 将以下两个文件添加到项目的"Classes"文件夹中并导入它们

MyAdMobAdsImpl.h

#ifndef __Unity_iPhone__MyAdMobAdsImpl__
#define __Unity_iPhone__MyAdMobAdsImpl__


void InitMyAdMob(UIView* p_rootView, UIViewController* p_rootController);
void DestroyMyAdMob();

#endif /* defined(__Unity_iPhone__MyAdMobAdsImpl__) */

MyAdMobAdsImpl.mm

#import "GADBannerView.h"
#import "GADInterstitial.h"
 
#include "MyAdMobAdsImpl.h"
 
NSString* _adMobID;
UIViewController* _adRootViewController;
GADBannerView* _adBanner;
GADInterstitial *_adInterstitial;
float _adBannerRelWidth;
float _adBannerRelHeight;
 
extern "C"
{
    void _initAds (const char* p_adMobID)
    {
        _adMobID = [NSString stringWithUTF8String:p_adMobID];
 
        _adBanner.adUnitID = _adMobID;
 
        _adInterstitial.adUnitID = _adMobID;
        GADRequest *request = [GADRequest request];
        [_adInterstitial loadRequest:request];
 
    }
 
    void _showInterstitialAd ()
    {
        [_adInterstitial presentFromRootViewController:_adRootViewController];
        // get next add
        _adInterstitial = [[GADInterstitial alloc] init];
        _adInterstitial.adUnitID = _adMobID;
        GADRequest *request = [GADRequest request];
        [_adInterstitial loadRequest:request];
    }
 
    void _showBannerAdTopRight ()
    {
        _adBanner.hidden = NO;
        // force refresh
        GADRequest *request = [GADRequest request];
        [_adBanner loadRequest:request];
    }
 
    void _hideBannerAds ()
    {
        _adBanner.hidden = YES;
     }
 
    float _getAdsRelativeWidth () { return _adBannerRelWidth; }
 
    float _getAdsRelativeHeight () { return _adBannerRelHeight; }
}
 
void InitMyAdMob(UIView* p_rootView, UIViewController* p_rootController)
{
    _adRootViewController = p_rootController;
    // Initialize the banner at the bottom of the screen.
    CGPoint origin = CGPointMake(0.0, 0.0);
    // Use predefined GADAdSize constants to define the GADBannerView.
    _adBanner = [[[GADBannerView alloc] initWithAdSize:kGADAdSizeBanner origin:origin] autorelease];
    [_adBanner setRootViewController:p_rootController];
    [p_rootView addSubview:_adBanner];
    // ios frame size is not rotated -> exchange width-height
    _adBannerRelWidth = kGADAdSizeBanner.size.width / p_rootView.frame.size.height;
    _adBannerRelHeight = kGADAdSizeBanner.size.height / p_rootView.frame.size.width;
    _adBanner.center = CGPointMake(_adBanner.center.x+
                                   MAX(p_rootView.frame.size.height-kGADAdSizeBanner.size.width,
                                       p_rootView.frame.size.width-kGADAdSizeBanner.size.width),
                                   _adBanner.center.y);
 
    // Initialize the interstitial ad
    _adInterstitial = [[GADInterstitial alloc] init];
}
 
void DestroyMyAdMob()
{
    _adBanner.delegate = nil;
    [_adBanner release];
 
    [_adInterstitial release];
}

这两个文件实现了 AdMob 逻辑。使用此代码,可以在右上角显示和隐藏横幅广告以及显示全屏广告。此外,使用 getAdsRelative* 您可以获得相对屏幕中横幅的大小 space(宽度为 0.1 意味着横幅需要 0.1*Screen.width 像素)。为简单起见,这些方法在第一步中没有引用,但如果需要,您可以使用它们。

  • 现在必须从 Unity 调用 "InitMyAdMob" 和 "DestroyMyAdMob" 方法 classes
  • 打开"UI/UnityAppController+ViewHandling.mm"文件
  • 在最后一个#include下面添加如下代码: 代码 (CSharp):

//// ******************* ////
//// *** AdMob START *** ////
//// ******************* ////
  #import "MyAdMobAdsImpl.h"
//// ******************* ////
//// *** AdMob END   *** ////
//// ******************* ////

  • 将以下代码添加到 "createViewHierarchy" 函数中,就在“[_window makeKeyAndVisible];”之前 代码 (CSharp):

 //// ******************* ////
    //// *** AdMob START *** ////
    //// ******************* ////
    InitMyAdMob(_rootView, _rootController);
    //// ******************* ////
    //// *** AdMob END   *** ////
    //// ******************* ////

  • 在"releaseViewHierarchy"函数的开头添加如下代码 代码 (CSharp):

//// ******************* ////
    //// *** AdMob START *** ////
    //// ******************* ////
    DestroyMyAdMob();
    //// ******************* ////
    //// *** AdMob END   *** ////
    //// ******************* ////

  • 第 3 步完成:p

    1. 疑难解答
    1. 如果你得到 "library not found for -liPhone-lib" 确保将它移到构建阶段选项卡的顶部->Link Binary With Libraries 下拉列表
    1. 如果你得到 "Undefined symbol ... _OBJC_CLASS_$_CTTelephonyNetworkInfo" 在 Build Phases 选项卡中添加 CoreTelephony ->Link Binary With Libraries 下拉列表
    1. 如果你在 NSObjCRuntime.h 或一些类似的 NSObjC* 文件中得到大约 20 个错误: 确保将添加到项目的文件的 'File Type' 下拉列表设置为 'Objective-C++ Source'(当您 select 一个文件时,在最右边的列中)。这样它就可以正确处理文件并使用正确的路径和内容。 来源:http://forum.thegamecreators.com/?m=forum_view&t=201075&b=41
    1. 在较新的 XCode 版本和较新的 AdMob 版本中,需要添加额外的库(EventKit.framework 和 EventKitUI.framework)。或者你会得到: “_OBJC_CLASS_$_EKEvent”,引用自: libGoogleAdMobAds.a(GADOpener.o) 中的 objc-class-ref “_OBJC_CLASS_$_EKEventEditViewController”,引用自: libGoogleAdMobAds.a(GADOpener.o)
    2. 中的 objc-class-ref

GitHub 上有一个项目:

Unity Admob Plugin

它易于使用,而且我已经成功了。

using admob;
...
Admob.Instance().initAdmob("admob banner id", "admob interstitial id");//admob id with format ca-app-pub-2796046890663330/756767388
Admob.Instance().showBannerRelative(AdSize.Banner, AdPosition.BOTTOM_CENTER, 0);