• iOS开发之OC和unity交互


    1、unity调用OC

     OC类代码

    // testUnity.h
    
    extern "C"{
        //声明一个方法
        void testUnityFunction(int index, const char *userName);
    }
    // testUnity.m
    
    extern "C"{
        void testUnityFunction(int index, const char *userName) {
            NSLog(@"接收到来自unity的传参");
        }
    }

    unity的C#文件代码

    #if UNITY_IOS
        //引入声明
        [DllImport("__Internal")]
        static extern void testUnityFunction (int index, string str);
    #endif
    
    //实现方法
    void Start() 
    {
        #if UNITY_IOS    
        testUnityFunction(1, "hello World");
        #endif
    }

    这样就可以直接实现unity调用OC。

    2、OC回调unity:这里我们使用函数指针接口方法进行回调,可以传参,也可以带返回参数

    C#文件代码

    void Start()
    {
        #if UNITY_IOS
        
        //设置回调托管函数指针
        eckShowPlayer handler = new eckShowPlayer(eckShowPlayerHandler);
        IntPtr showPlayer = Marshal.GetFunctionPointerForDelegate(handler);
        //调用OC的方法,将C#的回调方法函数指针传给OC
        eckRegisterRecieveGameCallback(showPlayer);
    
        #endif
    }
    
    #if UNITY_IOS
    
            //声明一个OC的注册回调方法函数指针的函数方法,每一个参数都是函数指针
        [DllImport("__Internal")]
        public static extern void eckRegisterRecieveGameCallback(
            IntPtr showPlayer
        );    
        
            //先声明方法、delegate修饰标记是回调方法
        [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
        public delegate void eckShowPlayer(string userId);
    
            //实现回调方法 MonoPInvokeCallback修饰会让OC通过函数指针回调此方法
        [AOT.MonoPInvokeCallback(typeof(eckShowPlayer))]
        static void eckShowPlayerHandler(string userId) 
        {
            Debug.Log("收到来自oc的参数  - "+userId );
        }
    
    #endif 

    OC代码

    // testUnity.h
    
    //定义一个名字参数和C#类一样的方法
    typedef void (*eckShowPlayerHandler) (const char *userId);
    
    extern "C"{
        /**
         设置回调游戏的托管函数
         */
        void eckRegisterRecieveGameCallback(eckShowPlayerHandler showPlayer);
    }
    // testUnity.m
    
    //生命一个静态变量存储回调unity的函数指针
    static eckShowPlayerHandler showPlayerBlock;
    
    extern "C"{
        /**
         设置回调游戏的托管函数
         */
        void eckRegisterRecieveGameCallback(eckShowPlayerHandler showPlayer)
        {
            showPlayerBlock = showPlayer;
        }
    }

    这样在OC想要回调游戏的是时候即可调用 showPlayerBlock 就行了。

    其实大概流程就是先将C#的函数指针存入OC内存,在OC需要回调unity的时候就可以使用不同的指针来回调不同的unity方法,我上面的例子是一个方法、同理可以传入多个方法指针,每个方法也可以添加返回值等。大家有不懂的可以留言和我交流哈。

  • 相关阅读:
    Centos-706防火墙端口操作
    Centos-7.6安装DotnetCore3.1
    Centos-610-源码安装GIT
    Centos-610-安装Jenkins2.222.4
    Centos610-安装NodeJs
    Windows:开发环境Word,PPT,EXCEL com+组件配置
    DCom配置我的电脑有个红色向下的箭头
    NPM包管理工具NRM
    Win10-Jvm调优之工具基本配置、使用(二)
    Win10-Jvm调优之工具基本配置、使用(一)
  • 原文地址:https://www.cnblogs.com/hecanlin/p/12800883.html
Copyright © 2020-2023  润新知