1. 程式人生 > >react-native-android-unity(二)建立unity專案,並匯出為android程式碼包,嵌入android專案中

react-native-android-unity(二)建立unity專案,並匯出為android程式碼包,嵌入android專案中

1.建立unity專案

給Main Camera新增指令碼Android,使用C#開發,指令碼內容如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;//使用DllImport必須引用

public class Android : MonoBehaviour {

    string toastText = "111111";

    [DllImport("androidunity")]//定義.so檔案裡面的方法:
    private static extern int addNum(int a,int b);

    void OnGUI (){
        int num = 0;
        if (GUI.Button (new Rect(Screen.width / 10 + 50,Screen.height / 10 + 50,Screen.width / 5,Screen.height / 5),"a button"))
        {
            num = addNum (2,2);
            toastText = num.ToString ();

        }
        GUI.Label (new Rect (Screen.width / 5 + 250,Screen.height / 5 + 250,Screen.width / 5,Screen.height / 5), toastText);


    }

    //called from android
    void CalledFromAndroid(string str){
        toastText = str;
    }

}
2.執行unity專案:
File->Build Settings
如下圖:

選擇執行平臺,然後點選Player Settings,右側出現配置選項:
依次修改:Other Settings下的Package Name: com.raudemo
Device Filter:ARMv7(為了引入android編譯的庫,實現unity和android通訊,需要選擇對應的還可以選擇x86,不過對應android的庫也要選擇x86)
修改完開始執行:Building And Run
截圖如下:

功能:有一個按鍵和一個很小的label,按鍵和label的字型顯示從android傳過來的string,以及呼叫向android傳送訊息
3.匯出android程式碼包:
File->Building And Settings,修改Build System為Gradle(new),選擇Export Project.點選下方export,選擇匯出目錄,即可。
4.android嵌入unity
         實現方式是將unity匯出的android程式碼包得部分程式碼拷入react-native內部android專案裡。匯出的程式碼截圖如下:

需要拷貝的程式碼有:
libs
assets
jniLibs
UnityPlayerActivity.java
UnityPlayerNativeActivity.java
UnityPlayerProxyActivity.java
Activity匯入會有報錯,需要在專案裡匯入libs下的unity-classes.jar。
右鍵unity-classes.jar,選擇Add As Library,如圖:

修改UnityActivity.java程式碼:
程式碼如下:
public class UnityActivity extends UnityPlayerActivity {
    private LinearLayout u3dLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unity);
        u3dLayout = (LinearLayout) findViewById(R.id.u3d_layout);
        u3dLayout.addView(mUnityPlayer);
        mUnityPlayer.requestFocus();
    }
}
至此,嵌入成功。

執行react-native程式,在手機上點選可跳轉到原生頁面,原生頁面左側即嵌入的unity程式。

程式碼包在系列文章第一篇