Unity中动态加载dll文件

除了简单地在Unity Editor中Add Component添加C#脚本关联到具体的GameObject外,如果脚本功能相对独立或复杂一点,可将脚本封装成dll文件,unity来调用该dll。
DLL,是Dynamic Link Library的缩写,Windows平台广泛存在,广泛使用,可以使用C#或C++来编写。
前提:VS安装有C#或C++开发工具包
1、Unity + C# dll

复制代码
 1 using System;
 2 
 3 namespace CSharpDll
 4 {
 5     public class Class1
 6     {
 7         public static string hello(string name)
 8         {
 9             return name;
10         }
11     }
12 }
复制代码

成功编译成dll文件,名字为CsharpDll.dll。
在unity中创建一个Plugins文件夹,所有的外部引用的dll组件必须要放在这个文件下,才能被using。
如果是C#封装的dll,就用 using的方式引用,如果是C++的dll,就DllImport[""]的方式来添加对dll的引用。
然后我在C#脚本中用这个dll:

复制代码
 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 using CSHarpDll;
 5 
 6 public class Test : MonoBehaviour
 7 {
 8     void OnGUI()
 9     {
10         // Load C# dll at runtime
11         if (GUILayout.Button("Test c# dll"))
12         {
13             Debug.Log(Class1.hello("hello world "));
14         }
15     }
16 }
复制代码

2、Unity + C++ dll

复制代码
1 # define _DLLExport __declspec (dllexport)  
2 # else  
3 # define _DLLExport __declspec (dllimport)  
4 #endif  
5  
6 extern "C" string _DLLExport hello(string name)
7 {
8     return name;
9 }
复制代码

成功编译后将生成的CppDll.dll 文件导入unity中的Plugins文件中
此时为C++的dll,就DllImport[""]的方式来添加对dll的引用:

复制代码
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;  //调用c++中dll文件需要引入

public class Test : MonoBehaviour {
    [DllImport("CppDll")] static extern string hello(string name);
 
    // Use this for initialization
    void Start () {
    
    }
    
    // Update is called once per frame
    void OnGUI()
    {
        if (GUILayout.Button("Test c++ dll"))
        {
            Debug.Log(hello("hello world"));
        }
    }    
}
复制代码

posted on   我来乔23  阅读(2605)  评论(6编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示