现在的位置: 首页 > 综合 > 正文

Unity中C#与JavaScript相互通信

2013年04月19日 ⁄ 综合 ⁄ 共 765字 ⁄ 字号 评论关闭

本文代码例子  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);
}

欢迎留言相互讨论问题

抱歉!评论已关闭.