Unity - Vibrate Android Device For Custom Duration


Unity provides a very cool function using which you can choose to vibrate the Android device for One full second. Below is the code to vibrate your Android device for One second on click of a GUI button:

using UnityEngine;
using System.Collections;

public class VibrateClass : MonoBehaviour {
    void OnGUI() {
        if (GUI.Button(new Rect(0, 10, 100, 32), "Vibrate!"))
            Handheld.Vibrate();
    }
}

Now, in case you want to change the duration of the vibration, you have two options i.e., call the Vibrate() method repetitively or build a native android plugin where in you can control the duration of the vibration. In case you are not aware of how to create an Android plugin for Unity, I have a post on that, do check it out here

The above mentioned link creates a plugin to share your app, you can add a method in the same activity class or can create a whole new plugin with the features you need along with custom duration vibration.

The code to be added in the activity class for custom duration vibration is as below:

import android.os.Vibrator;
 ...
 Vibrator v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
 // Vibrate for 500 milliseconds
 v.vibrate(500);


There is one more thing that needs to be done, which is to include the permission in the AndroidManifest.xml file

<uses-permission android:name="android.permission.VIBRATE"/>

Now try calling this method from your Unity code instead of the
Handheld.Vibrate();

Once you do that, you have your own plugin which is capable of adding vibration with any duration you like.

See you around
Share on Google+

About Sujit Horakeri

Sujit Horakeri is a game freak just like any other next door guy you would come across. He is a Web Developer by Profession, Game Developer by Choice.
Connect with him on:
    Blogger
    Facebook

2 comments:

  1. Hi, one question man.

    How would be implemented the one method?
    Please could you give me an example?

    ReplyDelete

  2. It's been barely a few months since the release of Fifa 17 game, and work has already started for the release of the next version of the FIFA

    series, the Fifa 18. It will obviously have some more added features and a few updates as well. You can check out the rumors about the new specs

    from my site here if you want Fifa 18 Download

    ReplyDelete