查看: 1962|回复: 0
打印 上一主题 下一主题

Unity3D 里 C# 和JS互相访问方法

[复制链接]

5552

主题

2

听众

8万

积分

首席设计师

Rank: 8Rank: 8

纳金币
-1
精华
11

最佳新人 活跃会员 热心会员 灌水之王 突出贡献

跳转到指定楼层
楼主
发表于 2012-5-2 14:42:47 |只看该作者 |倒序浏览
方法01
------------------------JS访问C#的变量-----------------------------
JS脚本:
import System.Reflection;

var ee = 0;

var ddf:GameObject;

function OnGUI ()

{

var targetController1:Component= ddf.GetComponent("ctrl");

var fieldInfo: FieldInfo=targetController1.GetType().GetField("csvalue");
if(GUI.Button(Rect(100,100,100,100),"Call"))

{

ee=fieldInfo.GetValue(targetController1);

print(ee.ToString());

}

}

C#脚本:
using UnityEngine;

using System.Collections;
public class ctrl : MonoBehaviour

{

public int csvalue = 100;

void Start ()

{

}
void Update ()

{
}

}
-----------------------c#访问JS变量------------------------
c#代码:
using UnityEngine;

using System.Collections;

using System;

using System.Reflection;
public class CtoJS : MonoBehaviour {
public GameObject tt;

public String moneycount;

public String boncount;

// Use this for initialization

void Start ()

{

Component AComponent = tt.GetComponent("CllisionsSomeThing");

FieldInfo fieldInfo = AComponent.GetType().GetField("MC");

FieldInfo fieldInfo1 = AComponent.GetType().GetField("BomCount");

moneycount = fieldInfo.GetValue(AComponent).ToString();

boncount= fieldInfo1.GetValue(AComponent).ToString();
print(moneycount);

print(boncount);

}
void Update ()

{

}

}

js代码:
#pragma strict
var MC = "sdfsdfs";

var BomCount = 1000;
function Start () {
}
function Update () {
}
-------------------------------------------------------------------------------------------------
方法02

兩個文件 test1.js 和 test2.cs
test1.js
Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/
-->function OnGUI()

{

if(GUI.Button(Rect(25,25,100,30),"JS Call CS" ))

{ var c = gameObject.GetComponent("test2");

c.PrintTest();

}

}



function testPrint() { print("CS Call JS");

}

test2.cs
Code highlighting produced by Actipro CodeHighlighter (freeware)

http://www.CodeHighlighter.com/
-->using UnityEngine;

using System.Collections;



public class test2: MonoBehaviour {
void OnGUI()

{

if(GUI.Button(new Rect(25,70,100,30), "CS Call JS"))

{

test1 c = (test1)gameObject.GetComponent("test1");

c.testPrint();

}

}



void PrintTest() {

print("JS Call CS");

}

}
分享到: QQ好友和群QQ好友和群 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
转播转播0 分享淘帖0 收藏收藏0 支持支持0 反对反对0
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

手机版|纳金网 ( 闽ICP备2021016425号-2/3

GMT+8, 2025-6-16 20:28 , Processed in 0.058840 second(s), 28 queries .

Powered by Discuz!-创意设计 X2.5

© 2008-2019 Narkii Inc.

回顶部