js要怎么在u3d中使用

JavaScript08

js要怎么在u3d中使用,第1张

代码如下:

JavaScript code?

#pragma strict

import System

import System.Runtime.InteropServices

import dLLTest //需要测试的dll文件的命名空间

function Start () {}

function Update () {}

function OnGUI(){

GUI.Label(Rect(10,10,200,50),"i="+Add(3,4)) //Add函数原型为int Add(int a,int b),为dll文件中的函数

}

@DllImport("dlltest") //需要测试的dll文件名称,文件原本带.dll后缀,但是网上查的一些例子都木有带,所以这里也木有带public static function Add(x:int,y:int):int{}

用js方法来实现,代码为:document.getElementById("t").style.color="red"说明:上面的"t"可以根据自己需要修改,具体代码参考: 登陆通行证 function chcolor(){ document.getElementById("t").style.color="red"}

在c#中一般会封装成dll文件对外提供接口调用,unity的js脚本也是这样的调用方式。

一、创建dll文件

1。打开vs文件->新建->项目->C#->类库,输入项目的名称,创建一个dll项目

2。引入 UnityEngine UnityEditor 这两个文件放在unity安装目录的Unity\Editor\Data\Managed路径下,

具体添加步骤:右键点击解决方案->添加引用->浏览

3。如果加入了UnityEngine UnityEditor,在项目中就可以using UnityEngine 和 UnityEditor;如果项目中不需要,也可以省略第二步

举例说明:

using System

using System.Collections.Generic

using System.Linq

using System.Text

using UnityEngine

using UnityEditor

using System.Collections

namespace dlltest

{

class Class2 : MonoBehaviour

{

void Start()

{

Debug.Log("this is unity call C# dll test!")

}

}

}

5。F5启动生成解决方案(debug或者release),把生成的dll放到unity工程的asset下;

6。如果继承了Monobehaviour的类在dll的子对象中有显示,这样就可以绑定到GameObject上了,如果是要引用dll的类,需要using 命名空间,名字一般和项目名称一致才能调用。