用C++为unity3D封装 .unitypachage

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中一样。

至此,结束。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值