u3d加载外部的c# DLL

环境: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、运行如下截图

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值