Unity开发的时候很多时候我们需要用到底层的一些功能,比如摄像,录音,震动等等,我们在Unity的层面是无法完成的。那么我们考虑到Unity是否可以直接调用到android方面的方法,替我们去完成我们所想要的操作。答案是有的,下面我带大家了解下unity对android的调用和一些问题的解答。
1.首先创建安卓项目
2.导入unity2d的class.jar
我使用的unity5.2.3,位置在于安装目录下的UnityEditorDataPlaybackEnginesandroidplayerVariationsmonoDevelopmentClassesclass.jar
3.Activity要继承UnityPlayerActivity
package com.sinyee.sdteam.clickshake; import android.app.Service; import android.os.Bundle; import android.os.Vibrator; import android.view.Menu; import com.unity3d.player.UnityPlayerActivity; public class MainActivity extends UnityPlayerActivity{ private Vibrator mVibrator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 震动 mVibrator = (Vibrator)getApplication().getSystemService(Service.VIBRATOR_SERVICE); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } //shake public void Shake(long milliseconds) { mVibrator.vibrate(milliseconds); } public void StopShake() { mVibrator.cancel(); } }
4.导出jar包
5.直接finish生成jar包。
6.在unity上AssetsPluginsAndroid中加入jar,xml,libs,res
7.unity上编写脚本代码
using UnityEngine; using System.Collections; public class testButton : MonoBehaviour { private AndroidJavaObject activity; // Use this for initialization void Start () { AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); activity = jc.GetStatic<AndroidJavaObject>("currentActivity"); } // Update is called once per frame void Update () { } void OnGUI() { if ( GUI.Button(new Rect(Screen.width / 2 - 20, Screen.height / 2 + 20, 100, 40), "点击震动")) { // 注意要用1000L,因为android那边的参数是long,不然会出错 activity.Call("Shake", 1000L); } if ( GUI.Button(new Rect(Screen.width / 2 - 20, Screen.height / 2 + 80, 100, 40), "取消震动")) { activity.Call("StopShake"); } } }
8.导出apk,配置注意如下
9.真机运行调试