一. 这种方法大家应该都知道,查看Unity的API也可以找到,并且Android和iOS的调用是一致的:
Handheld.Vibrate(); 此处调用的振动是固定时间,0.5秒,不可更改;
https://docs.unity3d.com/ScriptReference/Handheld.Vibrate.html
二. 可以通过AndroidJavaClass和AndroidJavaObject类实现,目前我的项目是2017.4.3f2,测试通过;(备注:此方法不需要编写Java代码,然后打包jar包并导入到Unity工程)
代码如下:
Vibrate类
public class Vibrate
{
public AndroidJavaClass unityPlayer;
public AndroidJavaObject currentActivity;
public AndroidJavaObject sysService;
public Vibrate()
{
unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
currentActivity = unityPlayer.GetStatic
vibrator = currentActivity.Call
// 目的是从Unity获取安卓设备的Vibrate权限,但此句不会执行
if (Application.isEditor)
Handheld.Vibrate();
}
public void DoVibrate()
{
vibrator.Call("vibrate");
}
public void DoVibrate(long milliseconds)
{
vibrator.Call("vibrate", milliseconds);
}
public void DoVibrate(long[] pattern, int repeat)
{
vibrator.Call("vibrate", pattern, repeat);
}
public void CancelVibrate()
{
vibrator.Call("cancel");
}
public bool HasVibrator()
{
return vibrator.Call
}
}
用法:
Vibrate vibrate = new Vibrate();
if(vibrate.HasVibrator())
{
// 调用振动
vibrate.DoVibrate();
// 振动500毫秒
vibrate.DoVibrate(500)
// 0延迟, 振动500毫秒,间隔200毫秒
long[] pattern = {0, 500, 200};
vibrate.DoVibrate(pattern, 0)
// 停止振动
vibrate.CancelVibrate();
}
如果有关于iOS在Unity中可以灵活调用振动的方法,希望可以留言回复,不想麻烦在xmind中写代码,关键是不会。。。XD