跨平台这种事情不管多NB, 总要有些与原生系统交互的方法, 比如 Unity3D与iOS消息交互方法.
一: 建立一个空的Unity工程.
File --> New Project
二: 编写脚本文件 (Test.cs)
在Project选项卡中, create ->C# script, 命名为Test, 双击, 编写此cs文件.
using UnityEngine;
using System.Collections; public class Main : MonoBehaviour { //声明两个Texture变量,图片资源在外面连线赋值
public Texture Button0;
public Texture Button1; // Use this for initialization
void Start () { } // Update is called once per frame
void Update () { } //这个方法用于绘制
void OnGUI() {
//绘制两个按钮
if(GUI.Button(new Rect(,,,),Button0))
{
//返回值为ture说明这个按钮被点击
SDK.ActivateButton0();
} //绘制两个按钮
if(GUI.Button(new Rect(,,,),Button1))
{
//返回值为ture说明这个按钮被点击
SDK.ActivateButton1();
}
}
}
同样的方法, 再生成一个脚本文件. SDK.cs
using UnityEngine;
using System.Runtime.InteropServices; public class SDK
{ //导出按钮以后将在xcode项目中生成这个按钮的注册,
//这样就可以在xocde代码中实现这个按钮点击后的事件。
[DllImport("__Internal")]
private static extern void _PressButton0 (); public static void ActivateButton0 ()
{ if (Application.platform != RuntimePlatform.OSXEditor)
{
//点击按钮后调用xcode中的 _PressButton0 ()方法,
//方法中的内容须要我们自己来添加
_PressButton0 ();
}
} //和上面一样
[DllImport("__Internal")]
private static extern void _PressButton1 (); public static void ActivateButton1 ()
{
if (Application.platform != RuntimePlatform.OSXEditor)
{
_PressButton1 ();
}
} }
三:绑定相关脚本到Main Camera
只拖动Test.cs文件到"Main Camera"上, 成功后, 可以在game view中看到效果图, 或者在Main Camera的Inspector中也能看到如: Test(Script)
ps: 在"Project"中添加图片文件作用button的图片, 也是用拖动的方法(选中Test.cs, 在Instpector中可以看到 Button0和1处无图片, 这时拖动图片文件到Button0和1上)
四: 导出iOS工程
Unity3D中的工作此时已经完成, 可以导出iOS工程了
File--> Build&Run
**:Unity3D中界面如下:
五: 在iOS工程中添加代码
添加两个文件 , 以接收Unity3D发来的消息
//
// MyView.h
// Unity-iPhone
//
// Created by willme on 13-10-15.
//
// #import <Foundation/Foundation.h> @interface MyView : NSObject @end
//
// MyView.m
// Unity-iPhone
//
// Created by willme on 13-10-15.
//
// #import "MyView.h" @implementation MyView //接收Unity3D 传递过来的信息
void _PressButton0()
{
UIAlertView *alert = [[UIAlertView alloc] init];
[alert setTitle:@"雨松MOMO程序世界"];
[alert setMessage:@"点击了第一个按钮"];
[alert addButtonWithTitle:@"确定"];
[alert show];
[alert release];
} void _PressButton1()
{ UIAlertView *alert = [[UIAlertView alloc] init];
[alert setTitle:@"雨松MOMO程序世界"];
[alert setMessage:@"点击了第二个按钮"];
[alert addButtonWithTitle:@"确定"];
[alert show];
[alert release];
} @end
**界面如下:
***代码来自 http://blog.csdn.net/xys289187120/article/details/6933456
最后的效果