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

Unity中C#与JavaScript相互通信

2013-08-03 09:29 288 查看
本文代码例子 http://vdisk.weibo.com/s/BDn59yfnBVHW-

首先给大家介绍一个名词 #pragma strict

#pragma strict

严谨编译模式

性能优化:JS中强制使用静态类型,脚本顶部添加#pragma strict。然后,unity将在脚本中禁用动态类型,强制使用静态类型,如果一个类型未知。Unity将报告编译错误。

可能会报这样的一个错误:(方法名) is not a member of 'UnityEngine.Component'. 解决这个错误的方法就是将 #pragma
strict 删掉就好了。

其中JS的文件必须在 这三个文件中的一个"Standard Assets"、 "Pro Standard Assets" 和 "Plugins" 没有的话自己创建就好。

下面是相互通信的代码

c#

using UnityEngine;
using System.Collections;

public class CSMain : MonoBehaviour {

	
	void OnGUI()
	{
		if(GUILayout.Button("JS"))
		{
			JSMain  jsScript = (JSMain)GetComponent("JSMain");
			jsScript.Test("shenqi");
			
			
		}
	}
	
	void CSTest(string test)
	{
		Debug.Log("CS" + test);
	}
	

}


JS

function OnGUI()
{
	if(GUI.Button( Rect(100,100,100,50),"CS"))
	{
		var csTest = this.GetComponent("CSMain");
		csTest.CSTest("fff");
	}
}

function Test(test:String)
{
	Debug.Log("JS " + test);
}


欢迎留言相互讨论问题
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: