一、编写安卓代码导出jar包,把jar包放到Unity工程Plugins/Android
package com.mekey.vibrator_as;
import android.app.Activity;
import android.app.Service;
import android.os.Vibrator;
public class Vibrator_as {
public static void getVibrator(Activity activity, long milliseconds) {
Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);
vib.vibrate(milliseconds);
}
}
二、Unity编写代码调用
using UnityEngine;
public class UnityCallAndroidVibrator : MonoBehaviour
{
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
getAndroidVibrator(100);
}
}
private void getAndroidVibrator(long vibratorTime)
{
AndroidJavaClass jc = new AndroidJavaClass("com.mekey.vibrator_as.Vibrator_as");
jc.CallStatic("getVibrator", getUnityContext(), vibratorTime);
}
private AndroidJavaObject getUnityContext()
{
AndroidJavaClass unityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject unityActivity = unityClass.GetStatic<AndroidJavaObject>("currentActivity");
return unityActivity;
}
void UntiyVibrator()
{
Handheld.Vibrate();
}
}
|