要實現遊戲SDK的接入,首先要解決的是Unity3D與原生IOS代碼之間的相互調用問題。Unity使用C#做爲開發語言,而IOS採用Objective-C做爲開發語言,如何讓C#調用OC代碼,或者讓OC調用C#代碼。所幸OC和C#都支持直接嵌入C/C++代碼,這裏使用C做爲二者之間的橋樑。 爲了簡化二者之間的接口調用和數據傳遞,在設計Unity與IOS SDK之間的接口時,Unity調用SDK只有一個接口,而SDK調用Unity也只有一個接口。因爲平臺方的SDK差別性較大,如何保證一個接口能夠解決問題?這裏咱們開發了一個通用SDK層,遊戲只會與通用SDK層交互,而由通用SDK層再與具體的平臺SDK對接。ios
#import "AppVestManager.h"
#import <AppVest/AppVest.h>
//固定代碼
#if defined(__cplusplus)
extern "C"{
#endif
extern void UnitySendMessage(const char *, const char *, const char *);
extern NSString* _CreateNSString (const char* string);
#if defined(__cplusplus)
}
#endif
@implementation AppVestManager
// SDK中初始化方法
-(void)initAppVest{
[[AppVest new] initAppVest];
}
// SDK中啓動代理方法(有參數都可以傳遞參數)
-(void)startProxy{
[[AppVest new] startProxy];
}
#if defined(__cplusplus)
extern "C"{
#endif
//字符串轉化的工具函數
NSString* _CreateNSString (const char* string)
{
if (string)
return [NSString stringWithUTF8String: string];
else
return [NSString stringWithUTF8String: ""];
}
char* _MakeStringCopy( const char* string)
{
if (NULL == string) {
return NULL;
}
char* res = (char*)malloc(strlen(string)+1);
strcpy(res, string);
return res;
}
static AppVestManager *myManager;
//供u3d調用的c函數 ( 因測試的sdk調用初始化爲不傳參方法,若是調用的sdk須要傳參調用,此處應相應修改成含參數方法)
void initAppVestAndStartIt()
{
if(myManager==NULL)
{
myManager = [[AppVestManager alloc]init];
}
[myManager initAppVest];
[myManager initAppVest];
}
#if defined(__cplusplus)
}
#endif
@end
複製代碼
5.打開unity 3d工程 (1)選擇左下方的Assets—>create—>c#Script新建文件名爲bridgeProject文件 c++
(2)建立好以後,點擊工程左上角的Main Camera,而後在右下角的Add Component中搜索BridgeProject文件進行添加,實現與Main Canera進行綁定,這樣遊戲啓動起來能夠調用該文件中方法,進行測試調用sdk狀況 c#
(3)而後使用MonoDevelop工具打開並編寫以下代碼,下載Unity3D時候會連帶安裝(這裏爲了測試寫了一個小按鈕) xcode
using UnityEngine;
using System.Collections;
public class bridgeProject : MonoBehaviour {
// Use this for initialization
void Start () {
print ("this is start");
// 調用AppVestManager初始化方法,進而調用ocAppVestManager中方法實現Unity3d調用ios SDK
AppVestManager.InitSDK ();
}
// Update is called once per frame
void Update () {
}
public void OnGUI() {
//開始按鈕
if(GUI.Button(new Rect(100,100,100,100),"button"))
{
//System.Console.WriteLine("hello world");
print("check button to start the appvest !");
}
}
}
複製代碼
using UnityEngine;
using System.Runtime.InteropServices;
public class AppVestManager : MonoBehaviour {
[DllImport("__Internal")]
private static extern void initAppVestAndStartIt();
//定義接口函數供遊戲邏輯調用
public static void InitSDK() {
if (Application.platform == RuntimePlatform.IPhonePlayer){ initAppVestAndStartIt();
}
}
}
複製代碼