Unity3D开发之“获取IOS设备所在的国家代码"

原地址:http://dong2008hong.blog.163.com/blog/static/469688272014021025578/

在前一段时间游戏开发中需要实现获取IOS设备所在的国家代码,方便服务端推送合适的语言的功能,在网上找了一些资料实现了上述功能,现在分享给大家。后面会给大家分享网络编程、数据库的应用、服务器的配置等的一些知识和注意事项。 
首先,这个功能Unity是没有提供现成的API,所以必须先制作一个IOS插件,然后才再Unity里面来调用Object-c实现了的功能。 
MyTool.h文件代码: 
#import <Foundation/Foundation.h> 
@interface MyTools : NSObject 
@end 
MyTool.m文件代码: 
#import "MyTools.h" 
@implementation MyTools 
char *_getCountryCode(){ 
    NSLocale *locale = [NSLocalecurrentLocale]; 
    NSString *countrycode = [localelocaleIdentifier]; 
    NSLog(@"国家代码:%@",countrycode); 
     
    const char *country = [countrycodeUTF8String]; 
    char *back =malloc(countrycode.length + 1); 
    char *back2 = back; 
    for (int i = 0;i<countrycode.length; i++) { 
        *back2 = country; 
        back2++; 
    } 
    *back2 = ''; 
    return back; 
} 
@end 
插件制作好以后,放到Plugins/IOS文件夹下,然后在Unity中创建MyTools.cs脚本 
代码如下: 
using UnityEngine; 
using System.Collections; 
using System.Runtime.InteropServices; 
public class MyTools : MonoBehaviour { 
[DllImport("__Internal")] 
private static extern string _getCountryCode(); 
public static string getCountryCode() 
{ 
return _getCountryCode(); 
} 
} 
在制作插件的时候一定要注意的问题就是,Object-c是不能直接传NSString数据类型给Unity的,你必须把NSString类型转化成char[]传给Unity。
原文地址:https://www.cnblogs.com/123ing/p/3829123.html