Minimum code for Android Alert Dialog Box in Unity

This was difficult to find, so here it is; the smallest snippet of code to present an AlertDialog (with OK button callback) to the user:

private class OnClickListener : AndroidJavaProxy {
    public readonly Action Callback;
    public OnClickListener(Action callback) : base("android.content.DialogInterface$OnClickListener") {
        Callback = callback;
    }
    public void onClick(AndroidJavaObject dialog, int id) {
        Callback();
    }
}

public override void ShowAlert(string title, string content) {
    AndroidJavaObject activity = null;
    using (var unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
        activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
    }
    activity.Call("runOnUiThread", new AndroidJavaRunnable(() => {
        AndroidJavaObject dialog = null;
        using (AndroidJavaObject builder = new AndroidJavaObject("android.app.AlertDialog$Builder", activity)) {
            builder.Call<AndroidJavaObject>("setTitle", title).Dispose();
            builder.Call<AndroidJavaObject>("setMessage", content).Dispose();
            builder.Call<AndroidJavaObject>("setPositiveButton", "OK", new OnClickListener(() => {
                Debug.Log("Button pressed");
            })).Dispose();
            dialog = builder.Call<AndroidJavaObject>("create");
        }
        dialog.Call("show");
        dialog.Dispose();
        activity.Dispose();
    }));
}

Note: I’m assuming all AndroidJavaObject objects need to be disposed (even when the same instance is returned in the case of the Builder), but that may not be the case.

You can remove the OnClickListener class and pass null as the final parameter for setPositiveButton if you do not need a callback.

Flap The Fish

I’m not so much a fan of Flappy Bird, but theres no denying that its a very addictive game. It’s interesting how such a small change (increasing the vertical movement speed, decreasing horizontal) from Helicopter can have such a huge impact on how the game plays.

I decided to give it a go building a similar game, initially as a joke and eventually convincing some friends to help meĀ improving it into something quite well polished and enjoyable. The game was built in under 2 weeks by 3 of us, here are some of the notable releases:

Initial release – play as a “blue bird”
Repackaged for portrait phones
Mutant Fish retheme
Improved model and shader experimentation
…lots of polish…
Current release

I’m really happy with how its turned out. Its released as a free Android game.

Unity 2014-02-23 18-47-05-03 - square
Download free from Google Play

Download free for Windows Phone

YouTube Trailer