Using Scripts in Unity3D
Scripting inside Unity is done by writing simple behaviour scripts in JavaScript, C#, or Boo. You can use one or all scripting languages in a single project, there is no penalty for using more than one. Unless stated otherwise, all the scripting examples are in JavaScript.
Creating New Scripts
Unlike other assets like Meshes or Textures, Script files can be created from within Unity. To create a new script, open the Assets-gt;Create-gt;JavaScript (or Assets-gt;Create-gt;C Sharp Script or Assets-gt;Create-gt;Boo Script) from the main menu. This will create a new script called NewBehaviourScript and place it in the selected folder in Project View. If no folder is selected in Project View, the script will be created at the root level.
You can edit the script by double-clicking on it in the Project View. This will launch your default selected editor in Unitys preferences. You do all your scripting in an external text editor, and not in Unity directly. To set the default script editor, change the drop-down item in Unity-gt;Preferences-gt;External Script editor.
These are the contents of a new, empty behaviour script:
function Update () {
}
A new, empty script does not do a lot on its own, so lets add some functionality. Change the script to read the following:
function Update () {
print('Hello World');
}
When executed, this code will print 'Hello World' to the console. But there is nothing that causes the code to be executed yet. We have to attach the script to an active GameObject in the Scene before it will be executed.
Attaching scripts to objects
Save the above script and create a new object in the Scene by selecting GameObject-gt;Create Other-gt;Cube. This will create a new GameObject called 'Cube' in the current Scene.
Now drag the script from the Project View to the Cube (in the Scene or Hierarchy View, it doesnt matter). You can also select the Cube and choose Component-gt;Scripts-gt;New Behaviour Script. Either of these methods will attach the script to the Cube. Every script you create will appear in the Component-gt;Scripts menu. If you have changed the name of your script, you will that name instead.
If you select the Cube and look at the Inspector, you will see that the script is now visible. This means it has been attached.
Press Play to test your creation. You should see the text 'Hello World' appear beside the Play/Pause/Step buttons. Exit play mode when you see it.
Manipulating the GameObject
A print() statement can be very handy when debugging your script, but it does not manipulate the GameObject it is attached to. Lets change the script to add some functionality:
function Update () {
transform.Rotate(0, 5*Time.deltaTime, 0);
}
If youre new to scripting, its okay if this looks confusing. These are the important concepts to understand:
function Update () {} is a container for code that Unity executes multiple times per second (once per frame).
transform is a reference to the GameObjects Transform Component.
transform 是游戏对象里的Transform组件的引用。
Rotate() is a function contained in the Transform Component.
The numbers in-between the commas represent the degrees of rotation around each axis of 3D space: X, Y, and Z.
Time.deltaTime is a member of the Time class that evens out movement over one second, so the cube will rotate at the same speed no matter how many frames per second your machine is rendering. Therefore, 5 * Time.deltaTime means 5 degrees per second.
With all this in mind, we can read this code as 'every frame, rotate this GameObjects Transform component a small amount so that it will equal five degrees around the Y axis each second.'
You can access lots of different Components the same way as we accessed transform already. You have to add Components to the GameObject using the Component menu. All the Components you can easily access are listed under Variables on the GameObject Scripting Reference Page.
The Power of Variables
Our script so far will always rotate the Cube 5 degrees each second. We might want it to rotate a different number of degrees per second. We could change the number and save, but then we have to wait for the script to be recompiled and we have to enter Play mode before we see the results. There is a much faster way to do it. We can experiment with the speed of rotation in real-time during Play mode, and its easy to do.
Instead of typing 5 into the Rotate() function, we will declare a speed variable and use that in the function. Change the script to the following code and save it:
var speed = 5.0;
function Update () {
transform.Rotate(0, speed*Time.deltaTime, 0);
}
Note that this is an example in Javascript. C# users should replace the keyword var with the type int. Now select the Cube and look at the Inspector. Notice how our speed variable appears.
This variable can now be modified directly in the Inspector, just like renaming a file in the file explorer. Select it, press Return and change the value. You can also right- or option-click on the value and drag the mouse up or down. You can change the variable at any time, even while the game is running.
Hit Play and try modifying the speed value. The Cubes rotation speed will change instantly. When you exit Play mode, youll see that your changes
剩余内容已隐藏,支付完成后下载完整资料
在unity3D中使用脚本
Unity中编写简单的行为脚本可以通过Javascript、C#或Boo来完成。你可以在一个项目中使用一种或全部的脚本语言,同时使用一种或多种脚本语言也是没有问题的。除非特别指定,所有的有关脚本的例子都是用Javascript来写的。(Javascript是官方推荐的脚本,当然你使用C#,Boo也是没有任何问题的。)
脚本文件不像网格或纹理资源那样,可以在Unity中创建。创建一个新的脚本,你需要从主菜单栏打开 Assets-gt;Create-gt;JavaScript (或Assets-gt;Create-gt;C Sharp Script 或 Assets-gt;Create-gt;Boo Script)。这样就创建了一个叫NewBehaviourScript的脚本。这个文件被放置在项目视图面板里被选中的文件夹中。如果在项目视图里没有选中的文件夹,脚本就被创建在根层级。
你可以双击项目视图面板的脚本来编辑。这将优先启动你的默认编辑器。你的所有脚本都在一个外部编辑器中来做而不是直接在Unity里进行。对于默认脚本编辑器的设置,通过下拉菜单Unity-gt;Preferences-gt;External Script editor进行。
以下是一个新创建的空脚本里的内容:
function Update () {
}
新建的空脚本本身还不能执行许多功能,所以我们需要添加一些功能语句。阅读下面的内容修改脚本:
function Update () {
print('Hello World');
}
当运行程序,这段代码会在控制台中打印'Hello World'。但这里还没有任何东西触发代码的执行。我们需要在其执行前先把这个代码附加到场景里的一个激活的游戏对象上。
附加脚本到对象上
保存上述脚本并在场景中通过选择GameObject-gt;Create Other-gt;Cube 来创建一个新对象。这将在当前场景里创建一个叫立方体(Cube)的游戏对象。
现在从项目视图面板中拖动之前的脚本到这个立方体上(在场景面板或层级面板操作都是可以的的)。你也可以选中立方体,然后选择Component-gt;Scripts-gt;New Behaviour Script。所有这些方法都可以将脚本附加到立方体Cube上。你创建的每一个脚本都会出现在Component-gt;Scripts菜单中。如果你改变了脚本的名称,菜单中的名字也将随之改变。
这时你选中立方体Cube并观察检视面板,你将会发现里面出现了这个脚本。这就意味着脚本已经被附加上了。
按下播放按钮测试你的场景。你会在 播放/暂停/单步按钮旁边看到'Hello World'。当你看到这个之后退出播放模式。
操纵游戏对象
print()语句在你调试脚本的时候非常方便。但是这个脚本还不能操纵附加他的游戏对象。让我们修改脚本添加一些功能。
function Update () {
transform.Rotate(0, 5*Time.deltaTime, 0);
}
如果你是脚本新手,这些代码看起来头疼是很正常的。以下是一些需要理解的重要概念:
function Update(){} 是一个用来存放Unity需要每秒执行多次代码的容器(每帧执行一次)。
Rotate()是一个Transform组件的一个函数。
在逗号分割数字分别代表三维空间中的X,Y,Z轴的旋转角度。
Time.deltaTime 是Time类的一个成员。用来指示事件一秒钟变化的量。所以无论你的机器一秒钟播放多少帧,立方体都会以相同的速度旋转。因此,5*Time.deltaTime的意思是5度/秒。
大脑中有了这些概念后,我们能够诠释这段代码为'每一帧,让游戏对象的Transform组件旋转一个小的角度,这样保持这个对象沿着Y轴每秒旋转5°'。
你可以使用我们访问transform成员相同的方式来访问更多不同的组件。你需要使用组件Component菜单来添加组件到游戏对象中。所有组件你都可以通过游戏对象脚本参考页中的列出的变量列表访问到。
变量的能力
到目前为止我们的脚本让立方体Cube保持每秒旋转5度。我们希望它能够每秒旋转不同的角度值。我们可以改变数值并保持。但是之后我们需要等待脚本被重新编译。然后我们还必须进入到播放模式才能够看到结果。现在有一种更快的方式来实现。我们可以在播放模式下实时试验旋转速度,这将会很容易做到。
我们将要声明一个速度speed变量并在函数中使用这个变量,而不是在Rotate()函数中使用5。像下面代码这样修改并保存:
var speed = 5.0;
function Update () {
transform.Rotate(0, speed*Time.deltaTime, 0);
}
注意这个例子是Javascript的写法。C#的用户需要把var关键字换成int。现在选中立方体Cube观察检视面板。注意看我们的speed变量是如何显示的。
这个变量现在可以在检视面板中直接被修改掉,就像在资源管理器里重命名一个文件一样。选中它,按下退格件修改值。你也可以在数值上右击或Option点击并拖动鼠标向上或向下。你可以再任何时刻改变变量甚至于游戏运行时。
点击播放按钮并试着修改speed的值。立方体的旋转速度将会立马变化。当你退出播放模式后,你会看到改变的值又恢复到你进入播放模式前的值上。这样你可以播放,调整和测试来找到最佳的值,然后一直使用这个值。
使用这种方式来改变检视面板里一个变量的值,这就意味着你能够重复使用一个脚本到许多对象上。每一个对象都使用不同的变量值。如果你附加脚本到多个立方体上。然后修改每一个立方体的speed变量,即便他们使用同一个脚本,他们会以不同的速度旋转。
访问其他组件
当编写一个脚本组件,你可以在这个游戏对象的脚本中访问其他的组件。
使用游戏对象的成员
你可以直接访问游戏对象类中的任何成员。在这里你能够访问到游戏对象类中的全部成员的一个列表。如果任何指定的类作物组件附加到游戏对象,你都可以通过在脚本中简单的输入成员名称来直接访问这个组件。例如,键入transform等价于gameObject.transform。游戏对象是通过编译器来确认的,除非你特别声明一个不同的游戏对象的引用。
键入this可以运行你写的脚本访问组件。键入this.gameObject获取对脚本附加的游戏对象的引用。你也可以通过简单键入gameObject来访问这个游戏对象。同理,使用this.transform和输入transform效果一样。如果你想访问一个非游戏对象成员的组件,你需要使用gameObject.GetComponent()关于这个的展开讨论在下一页。
很多组件在任何脚本中都能够直接被访问到。例如:你想要访问Transform组件的Translate函数,你可以输入transform.Translate()或者gameObject.transform.Translate()。这样之所有有效是因为所有的脚本被附加到一个游戏对象上。所以当你输入transform你能够隐性访问到被脚本化的游戏对象中的Transform组件。需要明确的是,你要输入gameObject.transform。不存在一种写法比其他写法更有优势,这全凭脚本编写人员的喜好决定。
使用GetComponent()
有不少组件没作为游戏对象类的成员被直接引用。所以你不能直接访问到他们,你需要明确的访问他们。你可以调用GetComponent('组件名称')来做这件事并把一个引用存放到结果中。当你想用获取另外一个脚本附属的游戏对象的引用时,这是一种常规做法。
假设你现在正在写B脚本这时你想做一个A脚本的引用(该脚本附加到同一游戏对象)。需要使用GetCompnonet()来实现这个引用。在B脚本中,你这样写:
scriptA = GetComponent('ScriptA');
访问其他脚本组件中的变量
所有被附加到你的游戏对象上的脚本都是组件。因此,你可以在一个脚本中使用GetComponent()的方法来获取对公共变量(和方法)。例如:
function Start () {
// Print the position of the transform component, for the gameObject this script is attached to
Debug.Log(gameObject.GetComponentlt;Transformgt;.().position);
}
在当前这个例子中GetComponentlt;Tgt;函数是用来反问Transform组件中的position属性的。同样的技术可以用来访问一个自定义脚本组件中的变量。
(MyClass.js)
public var speed : float = 3.14159;
(MyOtherClass.js)
function Start () {
// Print the speed variable from the MyClass script Component attached to the gameObject
Debug.Log(gameObject.GetComponentlt;MyClassgt;.().speed);
}
从Javascript访问C#中定义的变量
要访问C#脚本中定义的变量,那么在Javascript代码被编译之前,编译器中就必须已经存在C#的代码。Unity在不同的阶段执行编译,如在脚本参考Script Compilation部分所述。如果你想创建一个Javascript能够使用一个C#中的类或者变量。请把这个C#脚本放置到'Standard Assets'标准组件,'Pro Standard Assets'专业版标准组件或者'Plugins'插件文件夹中,并把Javascript文件放到这些文件夹以外的其他地方。在'Pro Standard Assets'专业版标准组件或者'Plugins'插件文件夹的代码会先编译,其他地方的代码之后编译。确保你的C#脚本中的定义先被编译好,在下一阶段Javascript脚本编译时已经被定义好了。
通常在'Pro Standard Assets'专业版标准组件或者'Plugins'插件文件夹中的代码,不管是(C#,Javascript还是Boo),都会先被编译,这样确保后续的编译脚本中能够使用。
优化变量访问
有些情况下,你可能会你的代码中多次使用GetComponent,或者每一帧调用几次。每一次调用GetDComponent函数内部都会做一些额外的步骤来获取你需要的组件。一个更为有效的做法是例如在你的start()函数中,存储组件的引用。你这样存储引用且不是直接访问它,这对于检查空引用也是一个好的做法。
(MyClass.js)
public var speed : float = 3.14159;
(MyOtherClass.js)
private var myClass : MyClass;
function Start () {
// Get a reference to the MyClass script Component attached to the gameObject
myClass = gameObject.GetComponentlt;MyClassgt;.();
}
function Update () {
// Verify that the reference is still valid and print the speed variable
if(myClass != null)
Debug.Log (myClass.speed);
}
静态变量
在你的类中也可以定义静态变量。这样对于这个特定的类里的静态变量就只会存在一份实例。这个静态变量可以被修改而不需要实例化一个类对象:
(MyClass.js)
static public var speed : float = 3.14159;
(MyOtherClass.js)
function Start () {
Debug.Log (MyClass.speed);<!--
剩余内容已隐藏,支付完成后下载完整资料
资料编号:[26264],资料为PDF文档或Word文档,PDF文档可免费转换为Word
您可能感兴趣的文章
- 饮用水微生物群:一个全面的时空研究,以监测巴黎供水系统的水质外文翻译资料
- 步进电机控制和摩擦模型对复杂机械系统精确定位的影响外文翻译资料
- 具有温湿度控制的开式阴极PEM燃料电池性能的提升外文翻译资料
- 警报定时系统对驾驶员行为的影响:调查驾驶员信任的差异以及根据警报定时对警报的响应外文翻译资料
- 门禁系统的零知识认证解决方案外文翻译资料
- 车辆废气及室外环境中悬浮微粒中有机磷的含量—-个案研究外文翻译资料
- ZigBee协议对城市风力涡轮机的无线监控: 支持应用软件和传感器模块外文翻译资料
- ZigBee系统在医疗保健中提供位置信息和传感器数据传输的方案外文翻译资料
- 基于PLC的模糊控制器在污水处理系统中的应用外文翻译资料
- 光伏并联最大功率点跟踪系统独立应用程序外文翻译资料
