您的位置:首页 > 移动开发 > Unity3D

Unity3D中C#和js方法相互调用

2014-11-18 22:24 351 查看
通过查找资料,Unity3D中C#和js要相互调用彼此的方法,js文件必须放在"Standard Assets"、 "Pro Standard Assets" 和 "Plugins"这三个文件夹中的任意一个。

在Scripts文件夹新建一个C#脚本 csTest :

public class csTest : MonoBehaviour {

void Start () {
jsTest js1 = gameObject.GetComponent<jsTest>();
js1.PrintJS("C#类中调用 ");
}

public void PrintCS (string str) {
print(str+":C#方法被调用");
}
}


在Standard Assets新建一个js脚本jsTest:

function Start(){
var cs1=gameObject.GetComponent("csTest");
cs1.PrintCS("从js中调用 ");
}

function PrintJS (str) {
print(str+": js方法被调用");
}


然将脚本都挂载到主摄像机上



C#和js脚本都是通过主摄像机这个游戏对象以组件的方式来获取的,也可以放在其他游戏对象上或者新建一个空的游戏对象。

运行游戏,查看控制台的打印信息。



相互调用成功!

js脚本为什么要放到这三个文件夹中?因为javascript脚本和C#脚本是不会编译到一起的。

查看官网的文档关于脚本编译顺序:http://docs.unity3d.com/Manual/ScriptCompileOrderFolders.html

The phases of compilation are as follows:-

Phase 1: Runtime scripts in folders called Standard Assets, Pro Standard Assets and Plugins.

Phase 2: Editor scripts in folders called Standard Assets/Editor, Pro Standard Assets/Editor and Plugins/Editor.

Phase 3: All other scripts that are not inside a folder called Editor.

Phase 4: All remaining scripts (ie, the ones that are inside a folder called Editor).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: