unity 中 c# 與 object-c 互動
C/C++可以直接與object-c互動,只需把檔案字尾寫成.mm就行了。c#又可以和C/C++互動,所以嘛。。。c#也就可以和object-c互動了。
1、在unity中 c#呼叫object-c 函式
首先,定義一個新建一個.mm檔案,然後在裡面定義一個C風格介面的函式,如
extern "C"
{
void testFunc(char* arg)
{
// 這裡可以呼叫object-c的函數了
// 如 [[ AlertView alloc] init]; ...
}
}
第二步,將這個mm檔案放到unity工程的Assets/Plugins/IOS路徑下。
第三步,宣告C函式。c#指令碼,呼叫上面的C介面,C函式裡面又呼叫object-c的函式,最終就能達到c#呼叫object-c的目的。但是,如何C#中並沒有testFunc這個函式,所以要先做函式宣告。
unity若要編譯ios專案,首先要匯出xcode工程,然後再由xcode匯出ipa安裝包。當你生產xcode工程時,你會發現,第二步中的mm檔案被引用到了xcdoe工程的Libraries下(你可以在xcdoe中的Libraries下找找看)。我的理解是這個mm檔案最終會被編譯成庫,那上面的testFunc函式就成了庫函式。在c#中要使用這個庫函式,首先要在檔案頭加入using System.Runtime.InteropServices;然後宣告函式:
[DllImort("__Internal")]
private static extern void testFunc(string arg);
第四步,呼叫函式。這時函式也在c#中宣告過了,使用時就可以直接呼叫了。
程式碼如下:
extern "C" { void test(char* title, char* msg, char* url) { NSString* nstitle = [[NSString alloc] initWithUTF8String:title]; NSString* nsmsg = [[NSString alloc] initWithUTF8String:msg]; NSString* nsurl = [[NSString alloc] initWithUTF8String:url]; UIAlertView* view = [[UIAlertView alloc] initWithTitle:nstitle message:nsmsg delegate:nil cancelButtonTitle:NSLocalizedString(@"Close", nil) otherButtonTitles:nil]; [view show]; } }
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
public class testscript : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
[DllImport("__Internal")]
private static extern void test (string title, string msg, string url);
void OnGUI()
{
if (GUI.Button (new Rect (100, 100, 100, 50), "test obj-c func")) {
test ("omytitle", "omymsg", "omyurl");
}
}
}
2、unity中 object-c 呼叫c#
UnitySendMessage("GameObjectName1", "MethodName1", "Message to send");
引數1:gameobject名字;引數2:回撥函式的名字;引數3:引數。同android開發中java回撥c#一樣,三個引數都是字串型別!但android開發中的第三個引數不能是null(若沒有引數,可以用空字串"",因為使用null程式會崩掉),這裡不知道能不能為null,還沒測試過。