實現unity3d導出到android studio工程並封裝爲library,供其餘工程導入module直接使用。
最終效果:java
最近看了下unity3d,關於unity3d和android端的交互參考了一些資料進行測試,現簡單總結記錄,同時以供參考。android
軟件版本以下:
unity3d:5.5.0f3
android studio:2.2android-studio
using UnityEngine;
using System.Collections;
public class CubeScripts : MonoBehaviour {
/// 定義旋轉速度
public float RotateSpeed=45;
/// 定義攝像機的最近距離
private float mNear=2.5F;
/// 攝像機當前距離
private float mDistance=5F;
/// 定義攝像機的最遠距離
private float mFar=7.5F;
/// 攝像機的縮放速率
private float mZoomRate=0.5F;
/// 主攝像機
private Transform mCamera;
/// 在Start()方法中咱們設定了遊戲體的名稱,由於咱們在
/// Android項目中須要用到這個名稱,同時獲取主相機對象
void Start ()
{
this.name="Main Cube";
mCamera=Camera.main.transform;
}
/// 在Update()方法中咱們讓Cube按照必定的速度進行旋轉
void Update ()
{
transform.Rotate(Vector3.up * Time.deltaTime * RotateSpeed);
}
/// 定義一個放大的方法供外部調用
public void ZoomIn()
{
mDistance-=mZoomRate;
mDistance=Mathf.Clamp(mDistance,mNear,mFar);
mCamera.position=mCamera.rotation * new Vector3(0,0,-mDistance)+transform.position;
}
/// 定義一個縮小的方法供外部調用
public void ZoomOut()
{
mDistance+=mZoomRate;
mDistance=Mathf.Clamp(mDistance,mNear,mFar);
mCamera.position=mCamera.rotation * new Vector3(0,0,-mDistance)+transform.position;
}
/// 觸摸立方體,調用android端的ShowDialog方法
void OnMouseDown()
{
ZoomOut();
Debug.Log("MOUSE DOWN");
using (AndroidJavaClass jc = new AndroidJavaClass("com.oden.u2as.UnityPlayerActivity"))
{
// jc.CallStatic("ShowDialog");
jc.CallStatic("ShowDialog", "str");
}
}
}複製代碼
注意修改包名
導出後工程加入如下方法:
爲unity工程中預先設置好的調用方法app
public static void ShowDialog(final String string) {
UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d("SYD", "ShowDialog: " + string);
AlertDialog.Builder builder = new AlertDialog.Builder(UnityPlayer.currentActivity)
.setMessage("哈哈哈這是Android的原生彈窗")
.setPositiveButton("肯定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
UnityPlayer.UnitySendMessage("Camera", "NativeTipClosed", "");
}
});
builder.show();
}
});
}複製代碼
apply plugin: 'com.android.library'
注:遇到報錯解決記錄:ide
public class MainActivity extends UnityPlayerNativeActivity {
private Button BtnZoomIn, BtnZoomOut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//獲取顯示Unity視圖的父控件
LinearLayout mParent = (LinearLayout) findViewById(R.id.UnityView);
//獲取Unity視圖
View mView = mUnityPlayer.getView();
//將Unity視圖添加到Android視圖中
mParent.addView(mView);
//放大
BtnZoomIn = (Button) findViewById(R.id.BtnZoomIn);
BtnZoomIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
UnityPlayer.UnitySendMessage("Main Cube", "ZoomIn", "");
}
});
//縮小
BtnZoomOut = (Button) findViewById(R.id.BtnZoomOut);
BtnZoomOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
UnityPlayer.UnitySendMessage("Main Cube", "ZoomOut", "");
}
});
}
}複製代碼