UnityでAndroidとiOSのアプリ間連携機能を使ったシェア機能の実装
Unityでのシェア機能実装
using UnityEngine; using System.Collections; using System.Runtime.InteropServices; public class MenuManager : MonoBehaviour { public void Share () { #if UNITY_IPHONE ShareForIOS (); #elif UNITY_ANDROID ShareForAndroid (); #endif } #if UNITY_IPHONE // iOS側のコードを呼び出すための処理 [DllImport("__Internal")] private static extern void Myapp_Share (string text, string url); void ShareForIOS () { string text = "Shareしたい文章"; string url = "http://www.example.com/"; Myapp_Share(text, url); } #endif #if UNITY_ANDROID void ShareForAndroid () { // Find the UnityPlayer and get the static current activity AndroidJavaClass cUnityPlayer = new AndroidJavaClass ("com.unity3d.player.UnityPlayer"); AndroidJavaObject oCurrentActivity = cUnityPlayer.GetStatic<AndroidJavaObject> ("currentActivity"); // Get defenitions of Intent and it's constructor. AndroidJavaObject oIntent = new AndroidJavaObject ("android.content.Intent"); // Call some methods oIntent.Call<AndroidJavaObject> ("setAction", "android.intent.action.SEND"); oIntent.Call<AndroidJavaObject> ("setType", "text/plain"); oIntent.Call<AndroidJavaObject> ("putExtra", "android.intent.extra.TEXT", "Shareしたい文章"); // Start the activity! oCurrentActivity.Call ("startActivity", oIntent); //Dispose them. Not sure if I need to do it or not... oIntent.Dispose (); oCurrentActivity.Dispose (); } #endif }
iOSプラグインの実装
プラグインの実装
- Assets/Plugins/iOS/Share.mm として以下ファイルを作成します。
- 標準ではMain,Twitter,Facebookなどが対象となっており、LINEも選択できるように別途ライブラリを使用します。
#import "LINEActivity.h" extern "C" { void Myapp_Share(const char *text, const char *url) { // NSStringに変換 NSString *_text = [NSString stringWithUTF8String:text]; NSString *_url = [NSString stringWithUTF8String:url]; // テキスト・URLの順に配列を作成する NSArray *actItems = [NSArray arrayWithObjects:_text, _url, nil]; // LINE用のライブラリを読み込む LINEActivity *lineActivity = [[LINEActivity alloc] init]; NSArray *myItems = [NSArray arrayWithObjects:lineActivity, nil]; // UIActivityViewを作成する UIActivityViewController *uiActivityViewController = [[[UIActivityViewController alloc] initWithActivityItems:actItems applicationActivities:myItems] autorelease]; // Unity画面の上にビューを表示させる [UnityGetGLViewController() presentViewController:uiActivityViewController animated:YES completion:nil]; } }
ライブラリの用意
- OopsMouse/LINEActivity · GitHubをダウンロードし展開します。
- iOSでビルドを行い、Classes以下にダウンロードしてLINEActivityディレクトリをコピーします。