美文网首页
Unity3D 嵌入iOS原生代码

Unity3D 嵌入iOS原生代码

作者: 木马不在转 | 来源:发表于2017-05-24 16:52 被阅读339次

如果原生iOS代码比较少,结构简单,建议将原生代码嵌入到unity工程中,毕竟往原生工程里嵌入unity工程还是比较麻烦的。

原生工程嵌入unity项目还是比较简单的,就三个步骤:

步骤一

在如下图文件夹里新建ARCKRAppController类继承UnityAppController 并删除.h文件,将.m改成.mm

步骤二

导入需要展示的VC,重写createUI方法,在里面完成逻辑。如下图:

步骤三
  • 在需要展示AR界面的类里引入如下框架(注意该类的.m也要改成.mm):
    #import <UI/UnityView.h>
    #import <UI/UnityViewControllerBase.h>
    #import "UnityAppController+ViewHandling.h"
    #import <UIKit/UIKit.h>
  • 加载AR界面
    [self.view addSubview:GetAppController().unityView];
    GetAppController().unityView.frame =self.view.frame;
    如果要在AR界面加入返回按钮或者其它view,可以在[GetAppController().unityView上添加
    搞定,是不是很简单!

unity和oc互调

1 首先iOS调Unity的方法
  • iOS中
    //参数1 场景中模型的名字
    //参数2 脚本名称方法
    //参数3 想unity传递一个char类型的数据
    UnitySendMessage("iOSSendMessageToUnity", "ChangeCameraDirection", "");
  • unity中
    public class iOSSendMessageToUnity : MonoBehaviour
    {
    public void ChangeCameraDirection(){
    Debug.Log(@"更改相机方向");
    }
    }
2 iOS调Unity的方法
using UnityEngine;  
using System.Runtime.InteropServices;  
  
public class UnitySendMessageToiOS : object {  
  
    //导出按钮以后将在xcode项目中生成这个按钮的注册  
    //iOS中的注册格式  
  
    [DllImport("__Internal")]  
    private static extern void _PressShareBtn();  
  
    public static void ShareSceneIniOS(){  
        if (Application.platform != RuntimePlatform.OSXEditor) {  
            _PressShareBtn ();  
        }  
    }  
}  
  
btton关联的脚本 和方法  
using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;  
  
public class MainScene : MonoBehaviour {  
  
    public GameObject shareBtn;  
  
    public void OnShareBtnClick(){  
        UnitySendMessageToiOS.ShareSceneIniOS ();   
    }  
    // Use this for initialization  
    void Start () {  
          
    }  
  
    // Update is called once per frame  
    void Update () {  
          
    }  
}  
  
然后到xcode里, 我创建了一个空的类 用来接收unity 发来的消息  
#import "ReceiveUnitySystemEvent.h"  
@interface ReceiveUnitySystemEvent ()  
  
@end  
  
@implementation ReceiveUnitySystemEvent  
  
void _PressShareBtn()  
{  
    UIAlertView *alert = [[UIAlertView alloc]init];  
    [alert setTitle:@"分享]; 
    [alert setMessage:@"点击了分享 按钮"];  
    [alert addButtonWithTitle:@"确定"];  
    [alert show];  
}  

原生工程导入引起的一些错误解决方法:

  1. __weak typeof(self) 编译报错

解决办法:工程文件 - build settings - Apple LLVM 5.0 - language - C language Dialect 改为GNU99


2.使用Masnory框架时编译运行报出错误:cannot use "@throw" with objective-c exceptions disabled 。这是unity工程不支持@try 或@throw

解决办法:修改target -> build settings -> All | Combined -> Apple LLVM Compiler 7.0 - Language 中 Enable Objective-C Exceptions 为YES

相关文章

网友评论

      本文标题:Unity3D 嵌入iOS原生代码

      本文链接:https://www.haomeiwen.com/subject/maroxxtx.html