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"));
            }
        }    
    }
  • 相关阅读:
    PAT顶级 1015 Letter-moving Game (35分)
    PAT顶级 1008 Airline Routes (35分)(有向图的强连通分量)
    PAT顶级 1025 Keep at Most 100 Characters (35分)
    PAT顶级 1027 Larry and Inversions (35分)(树状数组)
    PAT 顶级 1026 String of Colorful Beads (35分)(尺取法)
    PAT顶级 1009 Triple Inversions (35分)(树状数组)
    Codeforces 1283F DIY Garland
    Codeforces Round #438 A. Bark to Unlock
    Codeforces Round #437 E. Buy Low Sell High
    Codeforces Round #437 C. Ordering Pizza
  • 原文地址:https://www.cnblogs.com/MakeView660/p/12217618.html
Copyright © 2011-2022 走看看