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 2020-01-20 13:42  我来乔23  阅读(2443)  评论(6编辑  收藏  举报

导航