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

Unity3D中JavaScript与C#对比(三)

[复制链接]

435

主题

2

听众

6371

积分

高级设计师

Rank: 6Rank: 6

纳金币
6372
精华
0

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

跳转到指定楼层
楼主
发表于 2012-9-5 14:06:29 |只看该作者 |倒序浏览
这系列第三节,解释JavaScript和C#在unity3d游戏引擎中编程时有什么不同。建议你最好先去阅读第一和第二节,方便理解这节内容。



在第三节中,主要讲解用JavaScript和C#让一个GameObject向前移动有什么不同。现在我们来看一段使用JavaScript让一个GameObject向前移动的代码:



public var goTransform : Transform;

private var vel : int = 2;//how fast the game object is being moved



function Awake()  

{

//get this GameObject's Transform

goTransform = this.GetComponent(Transform);

}



// Update is called once per frame

functionUpdate()  

{

//moves the containing GameObject forward

goTransform.position.z= goTransform.position.z+ vel;

}



把这个脚本的目的是在每一个更新周期使goTransform的z轴坐标增加来控制让goTransform向前移动的,现在让我们看看用C#编写代码会是什么样的:



using UnityEngine;  

usingSystem.Collections;  

public classPawnMover : MonoBehaviour

{

public Transform goTransform;  

privateint vel = 2;//how fast the game object is being moved



void Awake()

{  

            //get this GameObject's Transform

goTransform = this.GetComponent<Transform>();  

}   



// Update is called once per frame

void Update()  

{  

//returns a CS1612 error

goTransform.position.z=goTransform.position.z+ vel;//<=returns a CS1612 error

//this is the right way to do it when using C#

goTransform.Translate(Vector3.forward * vel);//moves the containing GameObject forward



}

}  



这 里我们可以看到,在C#中不能像JavaScript脚本中那样直接改变goTransform的z轴坐标值来移动,这样会产生CS1612error, 因为我们是要改变一个值而不是引用该值。为了避免这个错误,在用C#编写脚本时,我们用方法移动GameObejct,比如Translate()、 Rotate()、 RotateAround()等等。这些方法都是Transform类得公共成员变量。

这节我希望我已经清楚的解释了两种语言在Untiy3D中编程时有什么不同,不要忘了第四章,我会告诉你JavaScript和C#执行暂停代码有什么不同。
分享到: QQ好友和群QQ好友和群 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
转播转播0 分享淘帖0 收藏收藏0 支持支持0 反对反对0
回复

使用道具 举报

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

关闭

站长推荐上一条 /1 下一条

手机版|纳金网 ( 闽ICP备08008928号

GMT+8, 2024-5-21 20:54 , Processed in 0.080508 second(s), 29 queries .

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

© 2008-2019 Narkii Inc.

回顶部