成都大红花-Unity3D游戏开发者

此博客主要记录我在Unity3D游戏开发中的一些经验和我对Unity3D游戏开发的一些理解。

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

在前一段时间游戏开发中需要实现获取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[i];
        back2++;
    }
    *back2 = '\0';
    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。


(转载请注明原文地址)

欢迎大家加入Unity技术交流群:3112035

                                                                                                                                                                                  ———— 大红花

                                                                                   2013.12.20


评论(1)

热度(2)