廢話不多說直接上代碼。
一 Xcode端的OC代碼
在Xcode里面新建一個空的工程(不會搞的百度一下),然后創建一個.h和.m文件,記住要把.m的后綴改成.mm(.mm文件和.m文件的區別就是:.mm文件除了可以包含Objective-C和C代碼以外,還可以包含C++代碼),這個類要繼承自NSObject
.h代碼如下:
// // UnityStoreKit.h // UnityStoreKit // // Created by mac on 2017/12/14. // Copyright © 2017年 mac. All rights reserved. // #import <Foundation/Foundation.h> #import <StoreKit/StoreKit.h> @interface UnityStoreKit : NSObject @end
.mm代碼如下:
// // UnityStoreKit.m // UnityStoreKit // // Created by mac on 2017/12/14. // Copyright © 2017年 mac. All rights reserved. // #import "UnityStoreKit.h" @implementation UnityStoreKit #if defined(__cplusplus) extern "C"{ #endif void _goComment() { if([SKStoreReviewController respondsToSelector:@selector(requestReview)]) {// iOS 10.3 以上支持 [SKStoreReviewController requestReview]; } else { // iOS 10.3 之前的使用這個 NSString *appId = @"1280215473"; NSString * nsStringToOpen = [NSString stringWithFormat: @"itms-apps://itunes.apple.com/app/id%@?action=write-review",appId];//替換為對應的APPID [[UIApplication sharedApplication] openURL:[NSURL URLWithString:nsStringToOpen]]; } } #if defined(__cplusplus) } #endif @end
在軟件內部進行星級評價是在IOS10.3之后的新特性。我們將這倆個文件導出到Unity里面的plugins文件夾下。把這個倆個文件所依賴的StoreKit在Unity里面給勾選上(勾上之后Unity打包成XCode文件的時候會自動把這個庫給引用上)並且平台選擇成IOS平台(這樣打包成IOS的時候才會打包這倆個文件)。如下圖所示:
二 Untiy里面的調用代碼
using UnityEngine; using System.Collections; using System.Runtime.InteropServices; public class UnityStoreKitMgr : MonoBehaviour { private static UnityStoreKitMgr _instance; public static UnityStoreKitMgr Instance{ get{ if(_instance==null) { GameObject go= new GameObject ("UnityStoreKitMgr"); _instance=go.AddComponent<UnityStoreKitMgr> (); DontDestroyOnLoad (go); } return _instance; } } [DllImport("__Internal")] private static extern void _goComment(); public void GoToCommnet() { #if UNITY_IPHONE _goComment(); #endif } }
[DllImport("__Internal")]
這個我也不是很清楚。。反正就是擴展那一類的貌似是調用dl的一些函數(必寫)。
_goComment()必須和.mm文件里面的函數要一樣。
三 調用的運行的截圖
四 IOS回調Untiy
只有一個方式:
UnitySendMessage("UnityStoreKitMgr","onCancel","params");
第一個參數:調用的Unity函數所在腳本綁定的游戲物體
第二個參數:調用的Unity函數名稱
第三個參數:調用的Unity函數參數(只能是字符串類型,和android一樣)