环境:window平台下,vs2017,unity2018.2
mac环境下操作差不多,此处就不写了
一、封装和加载纯逻辑库(和unity不相干)
1、新疆一个c#工程,因为我的unity提示要求在【编译器】环境下只支持netframework3.5,所以这里创建的时候我选择了3.5版本
2、添加如下代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace test_002
{
public class Class1
{
public static float add(float x, float y)
{
return x + y;
}
}
}
3、编译生成
4、将生成的dll拷贝到unity工程的Assets目录下,因为外部dll在unity的汇编集是第一批加载的,所以我们可以在unity的代码中直接引用其命名空间即可使用这个库,具体代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using test_002;
public class testCallDll : MonoBehaviour {
// Use this for initialization
void Start () {
//Class1是那个DLL的类名
Debug.Log("DLL:"+Class1.add(3.1f,2.2f));
}
// Update is called once per frame
void Update () {
}
}
测试结果如下:
二、封装和加载unity相关的功能库
上面加载的Dll,其实逻辑和unity没多大关系,如果我想封装一些和unity相关功能库,那么就需要如下处理:
1、右键引用,选择添加引用
2、选择浏览,将unity库添加进来,一般在你的unity的安装目录下,选择unityEngine.dll和unityEditor.dll
3、修改之前的dll代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//可以导入unity相关的库
using UnityEngine;
using UnityEditor;
namespace test_002
{
public class Class1
{
public static float add(float x, float y)
{
return x + y;
}
//添加一个cube
public static GameObject addCube()
{
GameObject ob = GameObject.CreatePrimitive(PrimitiveType.Cube);
Transform obTr = ob.GetComponent<Transform>();
obTr.position = new Vector3(0,0,0);
obTr.localScale = new Vector3(1,1,1);
obTr.rotation = Quaternion.Euler(new Vector3(0,0,0));
return ob;
}
}
}
4、重新编译dll,然后将其拷贝覆盖unity目录Assets下的动态库
5、修改unity中的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using test_002;
public class testCallDll : MonoBehaviour {
// Use this for initialization
void Start () {
//Class1是那个DLL的类名
Debug.Log("DLL:"+Class1.add(3.1f,2.2f));
//添加一个cube
GameObject ob=Class1.addCube();
ob.GetComponent<Transform>().parent = this.GetComponent<Transform>();
}
// Update is called once per frame
void Update () {
}
}
7、运行如下截图