1、在 VS 中新建一个类库 MyLib
2、新建一个 Class1
增加变量_value 和方法 SetValue
并点击生成解决方案
在输出窗口,可以看到 dll 路径
将 dll 拷贝到 Unity Assets 目录下。
3、在 Untiy 的脚本中引用 MyLib,就可以调用 Class1 中的方法了
现在,假如我要写一个类,继承于 MonoBehaviour,并且在 Unity 编辑器中使用,那又要怎么做呢。
打开刚刚新建的 MyLib 的类库,添加 UnityEngine.dll
新建类 Class2,引入 UnityEngine
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace MyLib
{
class Class2 : MonoBehaviour
{
public int test = 0;
void Start() {
Debug.Log("test: " + test);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
namespace MyLib
{
class Class2 : MonoBehaviour
{
public int test = 0;
void Start() {
Debug.Log("test: " + test);
}
}
}
重新生成解决方案,把 dll 拷贝到 Unity 目录下
在编辑器下就可以看到 Class2,和 test 变量
但是会出现错误提示:TypeLoadException: Could not load type ‘System.Runtime.Versioning.TargetFrameworkAttribute’ from assembly ‘MyLib’.
System.MonoCustomAttrs.GetCustomAttributesBase
只需要把 MyLib 中的目标框架改成 Unity 的,删除 using System.Threading.Tasks,重新生成一下 dll
错误不见了,可以正常运行