トップ «前の日記(2021-01-12) 最新 次の日記(2021-02-11)» 編集

Cocoa練習帳

iOS/iPhone/iPad/watchOS/tvOS/MacOSX/Android プログラミング, Objective-C, Cocoa, Swiftなど

2012|01|02|03|04|05|06|07|08|09|10|11|12|
2013|01|02|03|04|05|06|07|08|09|10|11|12|
2014|01|02|03|04|05|06|07|08|09|10|11|12|
2015|01|02|03|04|05|06|07|08|09|10|11|12|
2016|01|02|03|04|05|06|07|08|09|10|11|12|
2017|01|02|03|04|05|06|07|08|09|10|11|12|
2018|01|02|03|04|05|06|07|08|09|10|11|12|
2019|01|02|03|04|05|06|07|08|09|10|11|12|
2020|01|02|03|04|05|06|07|08|09|10|11|12|
2021|01|02|03|04|05|06|07|08|09|10|11|12|
2022|01|02|03|04|05|06|07|08|09|10|11|12|
2023|01|02|03|04|05|06|07|08|09|10|11|12|
2024|01|02|03|

2021-01-19 [Unity][iOS][Android]Unity Native Plug-insについて

Unity Plug-insは外部で作成したコードをUnityに組み込む仕組みで、Managed plug-insとNative plug-insの2種類ある。

大雑把に説明すると、Managed plug-insはC#のコードで、Native plug-insはiOSやAndroidなどのプラットフォーム固有のコードとなる。

Unityの特殊フォルダは以下のとおり。

Assets
アセットが収められるフォルダ。
Editor
ランタイムでなくエディタ用のスクリプトを格納するフォルダ。
Editor default resources
エディタ用リソースのフォルダ。
Gizmos
見えないデザインの詳細を可視化する際に利用するアイコンのフォルダ。
Plugins
プラグインを格納するフォルダ。
Resources
スクリプトで読み込むリソースのフォルダ。
Standard Assets
インポートした標準のアセットパッケージのフォルダ。
StreamingAssets
このフォルダに格納されたファイルはターゲットにコピーされ利用できる。

Native plug-insのネイティブ・ソースを決められた形式のフォルダに格納すると、自動的に統合される。

iOSの場合は、Assets/Plugins/iOS に、ファイル名のsuffix が.a、.m、.mm、.c、.cpp のものが対象となる。

例えば、Assets/Plugins/iOS/Utils.c というファイルを配置する。

float FooPluginFunction()
{
    return 5.0F;
}

このコードを呼び出すC#スクリプトは以下の通り。

using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
 
public class Utils : MonoBehaviour
{
    #if UNITY_IPHONE
    [DllImport ("__Internal")]
    private static extern float FooPluginFunction ();
    #endif
 
    void Awake () {
        #if UNITY_IPHONE
        print (FooPluginFunction ());
        #endif
    }
}

このコードはiOSフレームワークを追加で必要としていないので、iOSビルドすれば動作する。

Androidでは、JavaやKotlinのソースファイルをプラグインに追加できて、InspectorウィンドウのSelect platforms for plubinでAndroidのみ選択されている状態にすればいい。

例えば、Assets/Plugins/Android/Utils.java というファイルを配置する。

package com.example;
 
class Utils {
    public static double fooPluginFunction() {
        return 5.0;
    }
}

このコードを呼び出すC#スクリプトは以下の通り。

using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
 
public class Utils : MonoBehaviour
{
    void Awake () {
        #if UNITY_ANDROID
        using (AndroidJavaClass cls = new AndroidJavaClass("com.example.Utils")) {
            Debug.Log("FooPluginFunction: " + cls.CallStatic("fooPluginFunction"));
        }
        #endif
    }
}

_ ソースコード

GitHubからどうぞ。
https://github.com/murakami/workbook/tree/master/unity/AddOn - GitHub

トップ «前の日記(2021-01-12) 最新 次の日記(2021-02-11)» 編集