Unity3D: JavaScript->C# 或 C#->JavaScript的调用

来源:互联网 发布:csol mac版 编辑:程序博客网 时间:2024/06/07 01:12

        在进行Unity3D 编程时,有些情况下,我们需要访问另一个不是我们正在使用的编程语言的脚本。虽然强烈推荐将所有脚本转换成一种,但是知道如何从一个JavaScript类访问一个C#脚本及反过来的情况 是很有用的。


         首先要做的是将脚本放在project的正确目录。你要访问的脚本必须要放在Standard Assets 或者  Plugins目录(注:本人Unity4.2测试的时候,Unity是不允许新建 Plugins 目录的)。其他脚本放在这些目录的外面。完了之后,就可以像其他Component一样调用GetComponent() 方法。这里是一个JavaScript 例子:


//create a variable to access the C# script  private var csScript : CSharp1;     function Awake()  {      //Get the CSharp Script      csScript = this.GetComponent("CSharp1"); //Don't forget to place the 'CSharp1' file inside the 'Standard Assets' folder  }     //...  

C# 例子

using UnityEngine;  using System.Collections;     public class CSharp2 : MonoBehaviour   {      //create a variable to access the JavaScript script      private JS1 jsScript;          void Awake()      {          //Get the JavaScript component          jsScript = this.GetComponent<JS1>(); //Don't forget to place the 'JS1' file inside the 'Standard Assets' folder      }  //...  }  

         这些就是如何做的了。没有办法同时地获取C#和JavaScript的,因为其中一个脚本必须在Standard Assets 或者  Plugins 目录。这些目录中的脚本首先被编译,意味着这些脚本不能访问外面的脚本了,因为他们还没有编译。


译文原处



0 0