unity-导出插件的dll类库

  • Behavior Designer 那样,把插件的核心代码导出成 dll,然后给别人使用
  • 插件用 c# 写,就不需要像 c/c++ 那样担心跨平台问题,直接导出 dll 给编辑器用就行了

1. 新建 c# 类库


2. 引入 Unity 库

  • 右键 引用 -> 添加引用

  • 添加 UnityEngine.dll,路径unity安装路径下可以找到:D:\Unity\Editor\Data\Managed,(如果是编辑器dll,则选择 UnityEditor.dll


3. 随便写点代码,并生成

Class1.cs 文件中写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace DLLTest //一般加入命名空间来区分这个插件库
{
public class Class1
{
private int a;
public int total
{
get { return 5; }
}

public int Add(int a, int b)
{
return a + b;
}

public static int Clamp(int val, int min, int max)
{
return UnityEngine.Mathf.Clamp(val, min, max); //调用unity引擎的api
}

}
}

然后生成,在 DLLTest\DLLTest\bin\Debug 路径下可以找到生成dll:DLLTest.dll


4. Unity添加 DLLTest.dll 并使用

  1. DLLTest.dll unity工程的 Assets 目录下

  2. 然后随笔写个脚本测试

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    using UnityEngine;
    using System.Collections;
    using DLLTest;

    public class testDll : MonoBehaviour {
    void Start () {

    Class1 c = new Class1();
    Debug.LogFormat("--- add:{0}", c.Add(2,4));
    Debug.LogFormat("--- total:{0}", c.total);
    Debug.LogFormat("--- clamp:{0}", Class1.Clamp(1, 3, 5));
    }
    }
  3. done