Unity與IOS互動,Unity接入IOSSDK
阿新 • • 發佈:2020-07-28
近日學習Unity接入iosSdk,在此記錄下:
首先需要在xcode工程下寫入自己需要的程式碼:
iosview.h
#import <UIKit/UIKit.h> @interface IosViewController : UIViewController - (void) viewDidLoad; + (void) DoRecord; @end
iosview.mm
// // ViewController.mm #import "IosViewController.h" #import <HeroStatistics/HeroStatisticsManager.h> @interface IosViewController() { } @end @implementation IosViewController//OC字典轉json字串: - (NSString*)dictionaryToJson:(NSDictionary *)dic { NSError *parseError = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError]; return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; }- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end //必不可少的地方,Unity呼叫ios方法會在此處查詢方法名, //[DllImport("__Internal")] //private static extern void viewDidLoad(); //Unity端固定寫法:viewDidLoad 與下文中 viewDidLoad 一一對應; #if defined (__cplusplus) extern"C" { #endif void viewDidLoad() { NSLog(@" -unity call-- _viewDidLoad !!"); } void DoRecord(const char *keyStr,const char *valueStr) { NSLog(@" -unity call-- _DoRecord !!"); NSString *keystring = [[NSString alloc] initWithUTF8String:keyStr]; NSArray *keyarray = [keystring componentsSeparatedByString:@"#"]; NSString *valstring = [[NSString alloc] initWithUTF8String:valueStr]; NSArray *valarray = [valstring componentsSeparatedByString:@"#"]; NSLog(@"KeyString:%@", keystring); NSLog(@"valueString:%@", keystring); } void callUnity() { UnitySendMessage("Main Camera", "IosCallUnity", ""); } #if defined (__cplusplus) } #endif
.h 和.mm檔案一一對應
c#端程式碼:
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Runtime.InteropServices; public class GameRoot : MonoBehaviour { [DllImport("__Internal")] private static extern void viewDidLoad(); [DllImport("__Internal")] private static extern void DoRecord(string keyStr,string valueStr); [DllImport("__Internal")] private static extern void callUnity(); private void Awake() { viewDidLoad(); DoRecord("11#22#33", "key1#key2#key3"); callUnity(); } public void IosCallUnity() { Debug.Log("IOS Call Unity"); } }
至此,Unity和ios互相呼叫就完成了。
關於如何自動化匯入Framework和修改info.plist 請參考: