LoginSignup
99
101

More than 5 years have passed since last update.

C#スクリプトをDLL化してUnityで使う

Last updated at Posted at 2016-07-05

はじめに

C#をDLLにしてUnityで使おうとしたらいろいろハマったので記事にまとめてみました。

この記事のOSは Windows10, Unityのバージョンは Unity5.3.5f1 です.
Visual Studio 2015 Communityを使います。

DLLを作ってUnityで使うまでの流れ

新規プロジェクト作成 -> C#クラス作成 -> DLL作成 -> Unityに入れる -> 使う

1. C#プロジェクトを作成

DLLを作る準備として新規プロジェクトを作成します。

New Project 2016-07-05 17.56.43.png

Visual C# -> Class Library を選択してプロジェクト名を DLLTest にしてOKをクリック。

2. using namespace無しのDLLの作成

プロジェクトを作成するとClass1.csが作られているはずなので、これをを以下のように書き換えてDLL化することを考えます。
int値を返すstaticメソッドを1つだけ持つクラスです。

Class1.cs
namespace DLLTest
{
    public class Class1
    {
        public static int Hoge()
        {
            return 114514;
        }
    }
}

DLLの作成

まず、以下のbatchファイルを作成します。 名前はbuild.batとします。
smcs.bat、UnityEngine.dll、UnityEditor.dllはUnityのインストール場所にあるはずです.

build.bat
smcs.batのファイルパス -r:"UnityEngine.dllのファイルパス" -r:"UnityEditor.dllのファイルパス" -target:library -out:任意の名前.dll *.cs

image

build.batをClass1.csやbinフォルダのあるディレクトリに配置します.
image

build.batをダブルクリックするとdllが作られるので、これをUnityProjectの Assets/Plugins/ 以下に入れます。
DLLTest 2016-07-05 18.33.26.png


DLLを使う

Test.cs
using UnityEngine;
using System.Collections;
using DLLTest;

public class Test : MonoBehaviour
{
    void Start()
    {
        Debug.Log(Class1.Hoge());
    }
}

実行してみるとConsoleに正しい値が表示されることが確認できます。
image


3. using namespace有りのDLLの作成

using namespaceするコードをDLL化する場合、すこし手間がかかります。
例えば、何も考えずにusing UnityEngine;と書くと以下のようなエラーが出てしまいます。
image

これを回避するためにはリファレンスを追加する必要があります。

リファレンスの追加

まず、ソリューションエクスプローラーのReferencesを右クリックして Add References を選択します。
image

Browseを選んで Browseボタンをクリック。
image.png

UnityEngine.dllを選んでAddをクリック。
image

UnityEngine.dllが一覧に追加されるのでチェックを入れてそのままOK。

image.png

using UnityEngine;のところで出ていたエラーが消えます(完)
image

参考サイト

マネージド プラグイン
http://docs.unity3d.com/ja/current/Manual/UsingDLL.html

99
101
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
99
101