Unity与IOS交互,Unity接入IOSSDK

近日学习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 请参考:

https://www.cnblogs.com/MuniuTian/p/13372196.html

猜你喜欢

转载自www.cnblogs.com/MuniuTian/p/13391668.html