Unity调用IOS相关接口获取手机型号(CSharp)

实现简单的效果:点击Button,调用IOS AlertView,并显示硬件型号

具体实现:在脚本中定义2个外部方法,一个为弹出AlertView的,另一个则为返回字符串的

GUI中创建一个Button,并在点击时弹出调用外部函数,达到弹框效果


在C-Sharp定义了一个外部方法

DllImport("__Internal") 和extern是关键点

以下是C-Sharp脚本代码

using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;

public class Test : MonoBehaviour {
	
	private static string _buttonTitle = "press!!!!";

	[DllImport ("__Internal")]
	private static extern string _getDeviceName();

	[DllImport ("__Internal")]
	private static extern void _showAlertView(string str);
	// Use this for initialization
	void Start () {
	
		if(Application.platform==RuntimePlatform.IPhonePlayer)
		{

			print("Unity:"+_getDeviceName());


		}
	}


	void OnGUI ()
	{
		if (GUI.Button(new Rect (15, 10, 450, 100),_buttonTitle))
		{
			_showAlertView(_getDeviceName());
		}

		GUIStyle labelFont = new GUIStyle();    
		labelFont.normal.textColor = Color.white;
		labelFont.alignment = TextAnchor.MiddleCenter;  
		labelFont.fontSize = 30; 
		GUI.Label(new Rect(15, 150, 100, 100), _getDeviceName(), labelFont);
		
		
	}
	
	
	// Update is called once per frame
	void Update () {
	

	}
}

将上述脚本绑定至Main Camera,接着Build&Run一下(PS:记得是IOS的)



这时Unity帮我们打开了XCODE,我们需要做的是在里面添加一个新类,我在这用.mm

并在.mm中通过extern "C"标记接口


#import <Foundation/Foundation.h>

@interface CustomMethods : NSObject

@end


//
//  CustomMethods.mm
//  Unity-iPhone
//
//  Created by Dale_Hui on 13-12-13.
//
//

#import "CustomMethods.h"
#import <sys/utsname.h>

static struct utsname systemInfo;

extern "C"
{
    void _showAlertView(const char* str);
    char* _getDeviceName();
}
void _showAlertView(const char* str)
{
    
    UIAlertView * alertView=[[UIAlertView alloc]initWithTitle:@"Unity交互" message:[NSString stringWithUTF8String:str] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
    [alertView release];
    
    
}

char* _getDeviceName()

{
    
    uname(&systemInfo);
    
    char* deviceName=(char*)malloc(sizeof(char)*255);
    
    strcpy(deviceName, systemInfo.machine);
    
    return deviceName;
    
}


@implementation CustomMethods

@end

IOS里有个给Unity发送回调方法(异步方法)

UnitySendMessage("GameObjectName1", "MethodName1", "Message to send");

三个参数分别为: 对象名,函数名,传递的信息



Unity 调用IOS IAP(内购):   http://blog.chukong-inc.com/index.php/2012/01/05/unity3d-之iap/

有关extern "C"的解释:   http://blog.chinaunix.net/uid-21411227-id-1826909.html


你可能感兴趣的:(ios,脚本,unity,csharp,Unity获取IOS硬件型号)