Unity C#和OC互相調用


 Unity  兩種方式 一般都是組合使用

1.[DllImport("__Internal")]  C#調用oc
2.UnitySendMessage        oc調用C#
 
 1 C#調用oc 在C#腳本中
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;//引入

public class NewBehaviourScript : MonoBehaviour {
    [DllImport("__Internal")] 
    private static extern void CallOC();   //該方法為oc 中mm文件方法名稱
    // Use this for initialization
    void Start () {
        CallOC ();                                     //調用
    }
    
    // Update is called once per frame
    void Update () {
    
    }
}
 
在MM文件中

#import

// 函數實現

 #ifdef __cplusplus

 extern "C" {

     #endif

    

         void CallOC()

         {

             NSLog(@"調用到了OC");

             

         }

     #ifdef __cplusplus

     }

 #endif

 
 
2 oc調用unity中代碼  unity 幫我封裝好的
UnitySendMessage 在java通知unity 同樣可以使用 
首先在MM文件中
//這段就是加了一個按鈕 觸發一個方法 

 UIButton *but=[UIButton buttonWithType:UIButtonTypeRoundedRect];

    [but setImage:[UIImage imageNamed:@"button1.png"] forState:UIControlStateNormal];

    [but setImage:[UIImage imageNamed:@"button2.png"] forState:UIControlStateHighlighted];

    

    but.frame=CGRectMake(20, 20, 50, 60);

    [self.view addSubview:but];

   [but addTarget:self action:@selector(buttonCall) forControlEvents:UIControlEventEditingDidEnd];

//觸發方法

      -(void)buttonCall{

                 UnitySendMessage("Cube", "buttonCall", ""); //第一個參數 同時模型名稱 2 該模型掛的腳本方法名稱  3參數

        }

 
 
在C#中  該腳本 掛在一個Cube上
 
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
    void buttonCall () {
        Debug.Log("OC buttonCall")
    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM