• unity---接入Admob


    目录

    1.Admob SDK 下载地址

    2.将下载好的unityPackage sdk导入到unity里

    ​编辑

     3.解析依赖到项目中

    4.设置admob app ID

     5.android 测试Id

     6.IOS 测试ID

     7.测试 app ID

    8. SDK初始化与使用示例代码

    9.gradle 配置

    10. gradle 下载地址


    1.Admob SDK 下载地址

    Admob SDK 下载地址

    2.将下载好的unityPackage sdk导入到unity

    在 Unity 编辑器中打开您的项目,然后依次选择 Assets > Import Package > Custom Package,并找到您下载的 GoogleMobileAdsPlugin.unitypackage 文件。

     3.解析依赖到项目中

    在 Unity 编辑器中,依次选择 Assets > External Dependency Manager > Android Resolver > Resolve。Unity 外部依赖项管理器库会将声明的依赖项复制到 Unity 应用的 Assets/Plugins/Android 目录中。

    4.设置admob app ID

    在 Unity 编辑器中,从菜单中依次选择 Assets > Google Mobile Ads > Settings

     5.android 测试Id

     6.IOS 测试ID

     7.测试 app ID

    ca-app-pub-3940256099942544~3347511713

    8. SDK初始化与使用示例代码

    1. using UnityEngine;
    2. using GoogleMobileAds.Api;
    3. using System;
    4. using GoogleMobileAds.Common;
    5. using System.Collections.Generic;
    6. using UnityEngine.Events;
    7. using UnityEngine.UI;
    8. public class AdsContr : Singleton<AdsContr>
    9. {
    10. private readonly TimeSpan APPOPEN_TIMEOUT = TimeSpan.FromHours(4);
    11. private DateTime appOpenExpireTime;
    12. private AppOpenAd appOpenAd;
    13. private BannerView bannerView;
    14. private InterstitialAd interstitialAd;
    15. private RewardedAd rewardedAd;
    16. private RewardedInterstitialAd rewardedInterstitialAd;
    17. /*
    18. public UnityEvent OnAdLoadedEvent;
    19. public UnityEvent OnAdFailedToLoadEvent;
    20. public UnityEvent OnAdOpeningEvent;
    21. public UnityEvent OnAdFailedToShowEvent;
    22. public UnityEvent OnUserEarnedRewardEvent;
    23. public UnityEvent OnAdClosedEvent;
    24. */
    25. //Admob测试id ca-app-pub-3940256099942544~3347511713
    26. private const string open_android_test = "ca-app-pub-3940256099942544/3419835294";
    27. private const string open_ios_test = "ca-app-pub-3940256099942544/5662855259";
    28. private const string banner_android_test = "ca-app-pub-3940256099942544/6300978111";
    29. private const string banner_ios_test = "ca-app-pub-3940256099942544/2934735716";
    30. private const string interstitial_android_test = "ca-app-pub-3940256099942544/1033173712";
    31. private const string interstitial_ios_test = "ca-app-pub-3940256099942544/4411468910";
    32. private const string video_android_test = "ca-app-pub-3940256099942544/5224354917";
    33. private const string video_ios_test = "ca-app-pub-3940256099942544/1712485313";
    34. private const string video_interstitial_android_test = "ca-app-pub-3940256099942544/5354046379";
    35. private const string video_interstitial_ios_test = "ca-app-pub-3940256099942544/6978759866";
    36. //admob 正式id ca-app-pub-1111111111~222222222
    37. private const string open_android = "";
    38. private const string open_ios = "";
    39. private const string banner_android = "";
    40. private const string banner_ios = "";
    41. private const string interstitial_android = "";
    42. private const string interstitial_ios = "";
    43. private const string video_android = "ca-app-pub-11111111/22222222";
    44. private const string video_ios = "";
    45. public Text statusText;
    46. public bool isTest; //是否为测试模式
    47. private void Start()
    48. {
    49. if (!isTest)
    50. {
    51. //广告线程与unity主线程同步
    52. MobileAds.RaiseAdEventsOnUnityMainThread = true;
    53. //添加测试机
    54. /*
    55. List deviceIds = new List() { AdRequest.TestDeviceSimulator };
    56. #if UNITY_ANDROID
    57. deviceIds.Add("86BF82E91DB5A2AE32FB942B2B179E9F");
    58. #elif UNITY_IPHONE
    59. MobileAds.SetiOSAppPauseOnBackground(true);
    60. deviceIds.Add("");
    61. #endif
    62. RequestConfiguration requestConfiguration =
    63. new RequestConfiguration.Builder()
    64. .SetTagForChildDirectedTreatment(TagForChildDirectedTreatment.Unspecified)
    65. .SetTestDeviceIds(deviceIds).build();
    66. MobileAds.SetRequestConfiguration(requestConfiguration);
    67. */
    68. //初始化
    69. MobileAds.Initialize((InitializationStatus obj) =>
    70. {
    71. Debug.Log("sdk init success");
    72. MobileAdsEventExecutor.ExecuteInUpdate(() =>
    73. {
    74. //LoadBanner();
    75. //RequestInterstitial();
    76. RequestAndLoadRewardedAd();
    77. //RequestAndLoadAppOpenAd();
    78. });
    79. });
    80. //AppStateEventNotifier.AppStateChanged += OnAppStateChanged;
    81. }
    82. }
    83. private AdRequest CreateAdRequest()
    84. {
    85. return new AdRequest.Builder()
    86. .AddKeyword("unity-admob-game")
    87. .Build();
    88. }
    89. #region--------Banner Ads--------------------------------------------------
    90. public void RequestBannerAd()
    91. {
    92. PrintStatus("Requesting Banner ad.");
    93. string adUnitId;
    94. if (isTest)
    95. {
    96. #if UNITY_EDITOR
    97. adUnitId = "unused";
    98. #elif UNITY_ANDROID
    99. adUnitId = banner_android_test;
    100. #elif UNITY_IPHONE
    101. adUnitId = banner_ios_test;
    102. #else
    103. adUnitId = "unexpected_platform";
    104. #endif
    105. }
    106. else
    107. {
    108. #if UNITY_EDITOR
    109. adUnitId = "unused";
    110. #elif UNITY_ANDROID
    111. adUnitId = banner_android;
    112. #elif UNITY_IPHONE
    113. adUnitId = banner_ios;
    114. #else
    115. adUnitId = "unexpected_platform";
    116. #endif
    117. }
    118. // Clean up banner before reusing
    119. if (bannerView != null)
    120. {
    121. bannerView.Destroy();
    122. }
    123. // Create a 320x50 banner at top of the screen
    124. bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);
    125. // Add Event Handlers
    126. bannerView.OnBannerAdLoaded += () =>
    127. {
    128. PrintStatus("Banner ad loaded.");
    129. //OnAdLoadedEvent.Invoke();
    130. };
    131. bannerView.OnBannerAdLoadFailed += (LoadAdError error) =>
    132. {
    133. PrintStatus("Banner ad failed to load with error: " + error.GetMessage());
    134. //OnAdFailedToLoadEvent.Invoke();
    135. };
    136. bannerView.OnAdImpressionRecorded += () =>
    137. {
    138. PrintStatus("Banner ad recorded an impression.");
    139. };
    140. bannerView.OnAdClicked += () =>
    141. {
    142. PrintStatus("Banner ad recorded a click.");
    143. };
    144. bannerView.OnAdFullScreenContentOpened += () =>
    145. {
    146. PrintStatus("Banner ad opening.");
    147. //OnAdOpeningEvent.Invoke();
    148. };
    149. bannerView.OnAdFullScreenContentClosed += () =>
    150. {
    151. PrintStatus("Banner ad closed.");
    152. //OnAdClosedEvent.Invoke();
    153. };
    154. bannerView.OnAdPaid += (AdValue adValue) =>
    155. {
    156. string msg = string.Format("{0} (currency: {1}, value: {2}",
    157. "Banner ad received a paid event.",
    158. adValue.CurrencyCode,
    159. adValue.Value);
    160. PrintStatus(msg);
    161. };
    162. // Load a banner ad
    163. bannerView.LoadAd(CreateAdRequest());
    164. }
    165. public void DestroyBannerAd()
    166. {
    167. if (bannerView != null)
    168. {
    169. bannerView.Destroy();
    170. }
    171. }
    172. #endregion
    173. #region --------Interstitial Ads--------------------------------------------
    174. public void RequestAndLoadInterstitialAd()
    175. {
    176. PrintStatus("Requesting Interstitial ad.");
    177. string adUnitId;
    178. if (isTest)
    179. {
    180. #if UNITY_EDITOR
    181. adUnitId = "unused";
    182. #elif UNITY_ANDROID
    183. adUnitId = interstitial_android_test;
    184. #elif UNITY_IPHONE
    185. adUnitId = interstitial_ios_test;
    186. #else
    187. adUnitId = "unexpected_platform";
    188. #endif
    189. }
    190. else
    191. {
    192. #if UNITY_EDITOR
    193. adUnitId = "unused";
    194. #elif UNITY_ANDROID
    195. adUnitId = interstitial_android;
    196. #elif UNITY_IPHONE
    197. adUnitId = interstitial_ios;
    198. #else
    199. adUnitId = "unexpected_platform";
    200. #endif
    201. }
    202. // Clean up interstitial before using it
    203. if (interstitialAd != null)
    204. {
    205. interstitialAd.Destroy();
    206. }
    207. // Load an interstitial ad
    208. InterstitialAd.Load(adUnitId, CreateAdRequest(),
    209. (InterstitialAd ad, LoadAdError loadError) =>
    210. {
    211. if (loadError != null)
    212. {
    213. PrintStatus("Interstitial ad failed to load with error: " +
    214. loadError.GetMessage());
    215. return;
    216. }
    217. else if (ad == null)
    218. {
    219. PrintStatus("Interstitial ad failed to load.");
    220. return;
    221. }
    222. PrintStatus("Interstitial ad loaded.");
    223. interstitialAd = ad;
    224. ad.OnAdFullScreenContentOpened += () =>
    225. {
    226. PrintStatus("Interstitial ad opening.");
    227. //OnAdOpeningEvent.Invoke();
    228. };
    229. ad.OnAdFullScreenContentClosed += () =>
    230. {
    231. PrintStatus("Interstitial ad closed.");
    232. //OnAdClosedEvent.Invoke();
    233. };
    234. ad.OnAdImpressionRecorded += () =>
    235. {
    236. PrintStatus("Interstitial ad recorded an impression.");
    237. };
    238. ad.OnAdClicked += () =>
    239. {
    240. PrintStatus("Interstitial ad recorded a click.");
    241. };
    242. ad.OnAdFullScreenContentFailed += (AdError error) =>
    243. {
    244. PrintStatus("Interstitial ad failed to show with error: " +
    245. error.GetMessage());
    246. };
    247. ad.OnAdPaid += (AdValue adValue) =>
    248. {
    249. string msg = string.Format("{0} (currency: {1}, value: {2}",
    250. "Interstitial ad received a paid event.",
    251. adValue.CurrencyCode,
    252. adValue.Value);
    253. PrintStatus(msg);
    254. };
    255. });
    256. }
    257. public void ShowInterstitialAd()
    258. {
    259. if (interstitialAd != null && interstitialAd.CanShowAd())
    260. {
    261. interstitialAd.Show();
    262. }
    263. else
    264. {
    265. PrintStatus("Interstitial ad is not ready yet.");
    266. }
    267. }
    268. public void DestroyInterstitialAd()
    269. {
    270. if (interstitialAd != null)
    271. {
    272. interstitialAd.Destroy();
    273. }
    274. }
    275. #endregion
    276. #region --------open Ads----------------------------------------------------
    277. public bool IsAppOpenAdAvailable
    278. {
    279. get
    280. {
    281. return (appOpenAd != null && appOpenAd.CanShowAd() && DateTime.Now < appOpenExpireTime);
    282. }
    283. }
    284. public void OnAppStateChanged(AppState state)
    285. {
    286. Debug.Log("App State is " + state);
    287. MobileAdsEventExecutor.ExecuteInUpdate(() =>
    288. {
    289. if (state == AppState.Foreground)
    290. {
    291. ShowAppOpenAd();
    292. }
    293. });
    294. }
    295. public void RequestAndLoadAppOpenAd()
    296. {
    297. PrintStatus("Requesting App Open ad.");
    298. string adUnitId;
    299. if (isTest)
    300. {
    301. #if UNITY_EDITOR
    302. adUnitId = "unused";
    303. #elif UNITY_ANDROID
    304. adUnitId = open_android_test;
    305. #elif UNITY_IPHONE
    306. adUnitId = open_ios_test;
    307. #else
    308. adUnitId = "unexpected_platform";
    309. #endif
    310. }
    311. else
    312. {
    313. #if UNITY_EDITOR
    314. adUnitId = "unused";
    315. #elif UNITY_ANDROID
    316. adUnitId = open_android;
    317. #elif UNITY_IPHONE
    318. adUnitId = open_ios;
    319. #else
    320. adUnitId = "unexpected_platform";
    321. #endif
    322. }
    323. // destroy old instance.
    324. if (appOpenAd != null)
    325. {
    326. DestroyAppOpenAd();
    327. }
    328. // Create a new app open ad instance.
    329. AppOpenAd.Load(adUnitId, ScreenOrientation.Portrait, CreateAdRequest(),
    330. (AppOpenAd ad, LoadAdError loadError) =>
    331. {
    332. if (loadError != null)
    333. {
    334. PrintStatus("App open ad failed to load with error: " +
    335. loadError.GetMessage());
    336. return;
    337. }
    338. else if (ad == null)
    339. {
    340. PrintStatus("App open ad failed to load.");
    341. return;
    342. }
    343. PrintStatus("App Open ad loaded. Please background the app and return.");
    344. this.appOpenAd = ad;
    345. this.appOpenExpireTime = DateTime.Now + APPOPEN_TIMEOUT;
    346. ad.OnAdFullScreenContentOpened += () =>
    347. {
    348. PrintStatus("App open ad opened.");
    349. //OnAdOpeningEvent.Invoke();
    350. };
    351. ad.OnAdFullScreenContentClosed += () =>
    352. {
    353. PrintStatus("App open ad closed.");
    354. //OnAdClosedEvent.Invoke();
    355. };
    356. ad.OnAdImpressionRecorded += () =>
    357. {
    358. PrintStatus("App open ad recorded an impression.");
    359. };
    360. ad.OnAdClicked += () =>
    361. {
    362. PrintStatus("App open ad recorded a click.");
    363. };
    364. ad.OnAdFullScreenContentFailed += (AdError error) =>
    365. {
    366. PrintStatus("App open ad failed to show with error: " +
    367. error.GetMessage());
    368. };
    369. ad.OnAdPaid += (AdValue adValue) =>
    370. {
    371. string msg = string.Format("{0} (currency: {1}, value: {2}",
    372. "App open ad received a paid event.",
    373. adValue.CurrencyCode,
    374. adValue.Value);
    375. PrintStatus(msg);
    376. };
    377. });
    378. }
    379. public void DestroyAppOpenAd()
    380. {
    381. if (this.appOpenAd != null)
    382. {
    383. this.appOpenAd.Destroy();
    384. this.appOpenAd = null;
    385. }
    386. }
    387. public void ShowAppOpenAd()
    388. {
    389. if (!IsAppOpenAdAvailable)
    390. {
    391. return;
    392. }
    393. appOpenAd.Show();
    394. }
    395. #endregion
    396. #region--------reward Ads--------------------------------------------------
    397. public void RequestAndLoadRewardedAd()
    398. {
    399. string adUnitId;
    400. PrintStatus("Requesting Rewarded ad.");
    401. if (isTest)
    402. {
    403. #if UNITY_EDITOR
    404. adUnitId = "unused";
    405. #elif UNITY_ANDROID
    406. adUnitId = video_android_test;
    407. #elif UNITY_IPHONE
    408. adUnitId = video_ios_test;
    409. #else
    410. adUnitId = "unexpected_platform";
    411. #endif
    412. }
    413. else
    414. {
    415. #if UNITY_EDITOR
    416. adUnitId = "unused";
    417. #elif UNITY_ANDROID
    418. adUnitId = video_android;
    419. #elif UNITY_IPHONE
    420. adUnitId = video_ios;
    421. #else
    422. adUnitId = "unexpected_platform";
    423. #endif
    424. }
    425. // create new rewarded ad instance
    426. RewardedAd.Load(adUnitId, CreateAdRequest(),
    427. (RewardedAd ad, LoadAdError loadError) =>
    428. {
    429. if (loadError != null)
    430. {
    431. PrintStatus("Rewarded ad failed to load with error: " +
    432. loadError.GetMessage());
    433. return;
    434. }
    435. else if (ad == null)
    436. {
    437. PrintStatus("Rewarded ad failed to load.");
    438. return;
    439. }
    440. PrintStatus("Rewarded ad loaded.");
    441. rewardedAd = ad;
    442. ad.OnAdFullScreenContentOpened += () =>
    443. {
    444. PrintStatus("Rewarded ad opening.");
    445. //OnAdOpeningEvent.Invoke();
    446. };
    447. ad.OnAdFullScreenContentClosed += () =>
    448. {
    449. PrintStatus("Rewarded ad closed.");
    450. //OnAdClosedEvent.Invoke();
    451. };
    452. ad.OnAdImpressionRecorded += () =>
    453. {
    454. PrintStatus("Rewarded ad recorded an impression.");
    455. };
    456. ad.OnAdClicked += () =>
    457. {
    458. PrintStatus("Rewarded ad recorded a click.");
    459. };
    460. ad.OnAdFullScreenContentFailed += (AdError error) =>
    461. {
    462. PrintStatus("Rewarded ad failed to show with error: " +
    463. error.GetMessage());
    464. };
    465. ad.OnAdPaid += (AdValue adValue) =>
    466. {
    467. string msg = string.Format("{0} (currency: {1}, value: {2}",
    468. "Rewarded ad received a paid event.",
    469. adValue.CurrencyCode,
    470. adValue.Value);
    471. PrintStatus(msg);
    472. };
    473. });
    474. }
    475. public void ShowRewardedAd(Action act)
    476. {
    477. if (isTest)
    478. {
    479. act();
    480. }
    481. else
    482. {
    483. if (rewardedAd != null)
    484. {
    485. rewardedAd.Show((Reward reward) =>
    486. {
    487. act();
    488. PrintStatus("Rewarded ad granted a reward: " + reward.Amount);
    489. RequestAndLoadRewardedAd();
    490. });
    491. }
    492. else
    493. {
    494. PrintStatus("Rewarded ad is not ready yet.");
    495. RequestAndLoadRewardedAd();
    496. }
    497. }
    498. }
    499. #endregion
    500. #region--------reward Interstitial Ads-------------------------------------
    501. public void RequestAndLoadRewardedInterstitialAd()
    502. {
    503. PrintStatus("Requesting Rewarded Interstitial ad.");
    504. #if UNITY_EDITOR
    505. string adUnitId = "unused";
    506. #elif UNITY_ANDROID
    507. string adUnitId = video_interstitial_android_test;
    508. #elif UNITY_IPHONE
    509. string adUnitId = video_interstitial_ios_test;
    510. #else
    511. string adUnitId = "unexpected_platform";
    512. #endif
    513. // Create a rewarded interstitial.
    514. RewardedInterstitialAd.Load(adUnitId, CreateAdRequest(),
    515. (RewardedInterstitialAd ad, LoadAdError loadError) =>
    516. {
    517. if (loadError != null)
    518. {
    519. PrintStatus("Rewarded interstitial ad failed to load with error: " +
    520. loadError.GetMessage());
    521. return;
    522. }
    523. else if (ad == null)
    524. {
    525. PrintStatus("Rewarded interstitial ad failed to load.");
    526. return;
    527. }
    528. PrintStatus("Rewarded interstitial ad loaded.");
    529. rewardedInterstitialAd = ad;
    530. ad.OnAdFullScreenContentOpened += () =>
    531. {
    532. PrintStatus("Rewarded interstitial ad opening.");
    533. //OnAdOpeningEvent.Invoke();
    534. };
    535. ad.OnAdFullScreenContentClosed += () =>
    536. {
    537. PrintStatus("Rewarded interstitial ad closed.");
    538. //OnAdClosedEvent.Invoke();
    539. };
    540. ad.OnAdImpressionRecorded += () =>
    541. {
    542. PrintStatus("Rewarded interstitial ad recorded an impression.");
    543. };
    544. ad.OnAdClicked += () =>
    545. {
    546. PrintStatus("Rewarded interstitial ad recorded a click.");
    547. };
    548. ad.OnAdFullScreenContentFailed += (AdError error) =>
    549. {
    550. PrintStatus("Rewarded interstitial ad failed to show with error: " +
    551. error.GetMessage());
    552. };
    553. ad.OnAdPaid += (AdValue adValue) =>
    554. {
    555. string msg = string.Format("{0} (currency: {1}, value: {2}",
    556. "Rewarded interstitial ad received a paid event.",
    557. adValue.CurrencyCode,
    558. adValue.Value);
    559. PrintStatus(msg);
    560. };
    561. });
    562. }
    563. public void ShowRewardedInterstitialAd()
    564. {
    565. if (rewardedInterstitialAd != null)
    566. {
    567. rewardedInterstitialAd.Show((Reward reward) =>
    568. {
    569. PrintStatus("Rewarded interstitial granded a reward: " + reward.Amount);
    570. });
    571. }
    572. else
    573. {
    574. PrintStatus("Rewarded interstitial ad is not ready yet.");
    575. }
    576. }
    577. #endregion
    578. ///
    579. /// Log the message and update the status text on the main thread.
    580. ///
    581. private void PrintStatus(string message)
    582. {
    583. if (isTest)
    584. {
    585. Debug.Log(message);
    586. MobileAdsEventExecutor.ExecuteInUpdate(() =>
    587. {
    588. statusText.text = message;
    589. });
    590. }
    591. }
    592. }

    9.gradle 配置

    1. allprojects {
    2. repositories {
    3. maven { url 'https://dl.google.com/dl/android/maven2/' }
    4. google()
    5. maven { url "https://jitpack.io" }
    6. maven { url 'https://maven.aliyun.com/repository/jcenter' }
    7. jcenter()
    8. flatDir {
    9. dirs 'libs'
    10. }
    11. mavenLocal()
    12. maven {
    13. url "https://maven.aliyun.com/nexus/content/repositories/releases"
    14. }
    15. }
    16. }

    10. gradle 下载地址

    unity 升级gradle版本

  • 相关阅读:
    后端jar包部署常见运行和停止命令
    Go 语言函数、参数和返回值详解
    浅谈前端骨架屏方案
    【技术积累】HTML+CSS+JavaScript中的基础知识【三】
    门窗软件项目---竖中梃类
    用C++实现一个日期类
    MAC地址简介
    Spring事务的传播机制
    [附源码]JAVA毕业设计考研驿站网站(系统+LW)
    Spring是什么?程序如何解耦?
  • 原文地址:https://blog.csdn.net/lalate/article/details/127551843