zoukankan      html  css  js  c++  java
  • 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"));
            }
        }    
    }
  • 相关阅读:
    worker.properties配置
    uriworkermap.properties配置
    Apache Tomcat连接器-Web服务器操作方法
    x01.os.14: 时间都去哪儿了
    x01.os.13: 文件系统
    x01.os.12: 在 windows 中写 OS
    x01.os.11: IPC 路线图
    x01.os.10: 输入输出
    x01.os.9: 进程切换
    x01.os.8: 加载内核
  • 原文地址:https://www.cnblogs.com/MakeView660/p/12217618.html
Copyright © 2011-2022 走看看