LoginSignup
5
3

More than 1 year has passed since last update.

Swift で Unity の macOS の Native Plugin を作る

Posted at

Swift で Unity の macOS の Native Plugin を作る

  • Unity は Native Plugin を作成することで、Unity から提供されていない、OS 固有の機能を使用することができます
  • 例えば maxOS では、Bluetooth の利用などが出来るようになります
  • こちらの記事では、Swift だけで、Unity の iOS の Native Plugin を紹介しています

  • 上記の記事の iOS の Native Plugin のプロジェクトを拡張して、macOS 向けの Native Plugin を作成します
  • iOS 実機向けと、macOS 向けの Native Plugin を同時に開発し、Editor での動作確認を実現することで、開発効率の向上を狙っています
  • 今回は、iOS 向けに作成したプロジェクトをベースに、数字の文字列を整数型に変換する swiftPmPlugin_toNumber 関数を持つ macOS で利用可能な Native Pugin を作成します
  • リポジトリはこちら↓です

macOS の bundle をビルドする

スタート時の workspace の様子

  • Swift で作った SwiftPM のライブラリと、動作確認用の Native のアプリターゲットを含むプロジェクトがあります
  • アプリターゲットは今回は必須ではありません

start_workspace.png

Bundle のターゲットを作成する

  • macOS-Plugin project を作成しました
  • project は何でも良いです

macOS-Plugin_project.png

  • File > New > Target から Bundle を選んで作成します
  • ここでは、MacOsSwiftPmPlugin と命名しました

select_bundle.png

save_bundle.png

Package のリンク

  • bundle のターゲットを選択し、general から Frameworks に、SwiftPM のライブラリを追加します

link_bundle_framework.png

Header のリンク

  • MacOsSwiftPmPlugin 内に PrefixHeader.pch を作成します

make_pch.png

made_pch.png

  • @import {{Swift で作ったパッケージ名}}; を記述します
#ifndef PrefixHeader_pch
#define PrefixHeader_pch

// Include any system framework and library headers here that should be included in all compilation units.
// You will also need to set the Prefix Header build setting of one or more of your targets to reference this file.

@import SwiftPmPlugin; // <- 追加

#endif /* PrefixHeader_pch */
  • ビルドをすると Bundle が出力されます

created_bundle.png

  • nm コマンドを利用すると、swiftPmPlugin_toNumber のシンボルが含まれることを確認できます
$ nm /path/to/bundle/MacOsSwiftPmPlugin.bundle/Contents/MacOS/MacOsSwiftPmPlugin | grep swiftPmPlugin_toNumber
0000000000001fe0 T _swiftPmPlugin_toNumber

Unity に組み込む

  • サンプルプロジェクトの Unity の Plugins/macOS/ に作成した MacOsSwiftPmPlugin.bundle を配置しました

self_bundle.png

  • macOS の場合は、DllImport 時に、bundle 名を指定する必要があるため、#if で分けました
using System;
using System.Runtime.InteropServices;
using UnityEngine;

public class Cube : MonoBehaviour
{

#if UNITY_EDITOR_OSX
    [DllImport("MacOsSwiftPmPlugin")]
#elif UNITY_IOS
    [DllImport("__Internal")]
#endif
    private static extern long swiftPmPlugin_toNumber(string stringNumber);

    void Update()
    {
        Debug.Log("number: " + swiftPmPlugin_toNumber("30"));
    }
}
  • Unity Editor から 実行してエラーが出なければ、Native Plugin の作成成功です

さいごに

  • macOS の場合、一度 DllImport すると、Unity Editor を終了するまで保持されます
  • bundle の差し替えだけだと処理が変わらないので注意してください
  • ライブラリの開発時は、iOS 向けのライブラリと同様に、Native 向けのターゲットを Xcode で作成して、デバッグをすると効率的だと思います
5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3