Skip to content

Instantly share code, notes, and snippets.

@aVolpe
Created October 16, 2014 02:45
Show Gist options
  • Save aVolpe/707c8cf46b1bb8dfb363 to your computer and use it in GitHub Desktop.
Save aVolpe/707c8cf46b1bb8dfb363 to your computer and use it in GitHub Desktop.
Vibration for Unity3d with Android native Call, with fallback to Handlheld.Vibrate()
using UnityEngine;
using System.Collections;
public static class Vibration
{
#if UNITY_ANDROID && !UNITY_EDITOR
public static AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
public static AndroidJavaObject currentActivity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
public static AndroidJavaObject vibrator = currentActivity.Call<AndroidJavaObject>("getSystemService", "vibrator");
#else
public static AndroidJavaClass unityPlayer;
public static AndroidJavaObject currentActivity;
public static AndroidJavaObject vibrator;
#endif
public static void Vibrate()
{
if (isAndroid())
vibrator.Call("vibrate");
else
Handheld.Vibrate();
}
public static void Vibrate(long milliseconds)
{
if (isAndroid())
vibrator.Call("vibrate", milliseconds);
else
Handheld.Vibrate();
}
public static void Vibrate(long[] pattern, int repeat)
{
if (isAndroid())
vibrator.Call("vibrate", pattern, repeat);
else
Handheld.Vibrate();
}
public static bool HasVibrator()
{
return isAndroid();
}
public static void Cancel()
{
if (isAndroid())
vibrator.Call("cancel");
}
private static bool isAndroid()
{
#if UNITY_ANDROID && !UNITY_EDITOR
return true;
#else
return false;
#endif
}
}
@SamKyada
Copy link

SamKyada commented Sep 14, 2021

'Vibration' is missing the class attribute 'ExtensionOfNativeClass'!
how to Solve this error.......
Unity 2020.3.17f1

@khOsman1917
Copy link

Thank you😊

@maryphun
Copy link

Doesn't expect this still work in 2022.
You're a hero

@diliupg
Copy link

diliupg commented Jan 21, 2022

@SamKyada , read the reply by @agustinaA-Lopez

@pflosch
Copy link

pflosch commented Dec 19, 2023

meanwhile 2023, Android14, copy, paste, works like a charm.
Thanks @aVolpe , you're the man...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment