1.第一步:使用Visual Studio 生成dll文件,具体步骤如下:
(1-1)打开编译器,新建 -->项目-->模板 -->Visual C++ -->Win32项目
(1-2)新建头文件:TestDLL.h
#ifndef _TestDLLForUnity_H_
#define _TestDLLForUnity_H_
#ifdef TESTDLL_EXPORTS
#define EXPORTS_TESTDLL _declspec( dllexport )
#else
#define EXPORTS_TESTDLL _declspec(dllimport)
#endif
extern"C" EXPORTS_TESTDLL int Add(int a, int b);
#endif
(1-3)新建源文件:TestDLL.cpp
#include "TestDLL.h"
int Add(int a, int b)
{
return (a + b);
}
(1-4)s生成DLL文件
【说明】:
(1)为什么是x64后面说明。
(2)生成的dll文件在工程的根目录 x64/Debug/TestDLLForUnity.dll
2.第二步:打开Unity3D编译器,更改运行平台,把生成的dll文件添加到Asserts/Plugins/文件夹下,编辑一个脚本测试DLL是否达到理想效果。
test.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices; (必须添加)
public class test : MonoBehaviour
{
[DllImport("TestDLLForUnity")]
private static extern int Add(int x, int y);
int ret = 0;
// Use this for initialization
void Start ()
{
ret = Add(5, 7);
Debug.LogFormat("ret = {0}", ret);
}
// Update is called once per frame
void Update ()
{
}
}
【说明】:本人所使用 的unity编译器为64bit,所以编译生成dll时也要是64bit的平台,运行时也要保持一致。
3.第三步:把资源文件封装成一个Unity3D的 .unitypackage ,具体步骤如下:
(不需要的可以去掉勾选)
4.最后,测试生成的资源包。
新建一个unity工程,导入刚刚生成的资源包CalAdd.unitypackage,写一个脚本,调用方式和test.cs中一样。
至此,结束。