打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Using Scripts 使用脚本

This is a short introduction on how to create and utilize scripts in a project. For detailed information about the Scripting API, please view the Scripting Reference. For detailed information about creating game play through scripting, please view the Creating Gameplay page of this manual.

本篇是一份关于如何在项目中创建和使用脚本的简介。要了解关于脚本的详细信息请查看 脚本手册 。对于通过脚本创建游戏的详细资料请查看手册里的 创建游戏 的页面。

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.

Unity中编写简单的行为脚本可以通过Javascript、C#或Boo来完成。你可以在一个项目中使用一种或全部的脚本语言,同时使用一种或多种脚本语言也是没有问题的。除非特别指定,所有的有关脚本的例子都是用Javascript来写的。(Javascript是官方推荐的脚本,当然你使用C#,Boo也是没有任何问题的。)

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->Create->JavaScript (or Assets->Create->C Sharp Script or Assets->Create->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.

脚本文件不像网格或纹理资源那样,可以在Unity中创建。创建一个新的脚本,你需要从主菜单栏打开 Assets->Create->JavaScript (或Assets->Create->C Sharp Script 或 Assets->Create->Boo Script)。这样就创建了一个叫NewBehaviourScript的脚本。这个文件被放置在项目视图面板里被选中的文件夹中。如果在项目视图里没有选中的文件夹,脚本就被创建在根层级。

You can edit the script by double-clicking on it in the Project View. This will launch your default selected editor in Unity's 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->Preferences->External Script editor.

你可以双击项目视图面板的脚本来编辑。这将优先启动你的默认编辑器。你的所有脚本都在一个外部编辑器中来做而不是直接在Unity里进行。对于默认脚本编辑器的设置,通过下拉菜单Unity->Preferences->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 let's 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.

当运行程序,这段代码会在控制台中打印"Hello World"。但这里还没有任何东西触发代码的执行。我们需要在其执行前先把这个代码附加到场景里的一个激活的游戏对象上。

Attaching scripts to objects 附加脚本到对象上

Save the above script and create a new object in the Scene by selecting GameObject->Create Other->Cube. This will create a new GameObject called "Cube" in the current Scene.

保存上述脚本并在场景中通过选择GameObject->Create Other->Cube 来创建一个新对象。这将在当前场景里创建一个叫立方体(Cube)的游戏对象。

Now drag the script from the Project View to the Cube (in the Scene or Hierarchy View, it doesn't matter). You can also select the Cube and choose Component->Scripts->New Behaviour Script. Either of these methods will attach the script to the Cube. Every script you create will appear in the Component->Scripts menu. If you have changed the name of your script, you will that name instead.

现在从项目视图面板中拖动之前的脚本到这个立方体上(在场景面板或层级面板操作都是可以的的)。你也可以选中立方体,然后选择Component->Scripts->New Behaviour Script。所有这些方法都可以将脚本附加到立方体Cube上。你创建的每一个脚本都会出现在Component->Scripts菜单中。如果你改变了脚本的名称,菜单中的名字也将随之改变。

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.

这时你选中立方体Cube并观察检视面板,你将会发现里面出现了这个脚本。这就意味着脚本已经被附加上了。

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.

按下播放按钮测试你的场景。你会在 播放/暂停/单步按钮旁边看到"Hello World"。当你看到这个之后退出播放模式。

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. Let's change the script to add some functionality:

print()语句在你调试脚本的时候非常方便。但是这个脚本还不能操纵附加他的游戏对象。让我们修改脚本添加一些功能。

function Update () {    transform.Rotate(0, 5*Time.deltaTime, 0);} 

If you're new to scripting, it's okay if this looks confusing. These are the important concepts to understand:

如果你是脚本新手,这些代码看起来头疼是很正常的。以下是一些需要理解的重要概念:

  1. function Update () {} is a container for code that Unity executes multiple times per second (once per frame).
    function Update(){} 是一个用来存放Unity需要每秒执行多次代码的容器(每帧执行一次)。
  2. transform is a reference to the GameObject's Transform Component.
    transform 是游戏对象里的Transform组件的引用。
  3. Rotate() is a function contained in the Transform Component.
    Rotate()是一个Transform组件的一个函数。
  4. The numbers in-between the commas represent the degrees of rotation around each axis of 3D space: X, Y, and Z.
    在逗号分割数字分别代表三维空间中的X,Y,Z轴的旋转角度。
  5. 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.
    Time.deltaTime 是Time类的一个成员。用来指示事件一秒钟变化的量。所以无论你的机器一秒钟播放多少帧,立方体都会以相同的速度旋转。因此,5*Time.deltaTime的意思是5度/秒。

With all this in mind, we can read this code as "every frame, rotate this GameObject's Transform component a small amount so that it will equal five degrees around the Y axis each second."

大脑中有了这些概念后,我们能够诠释这段代码为"每一帧,让游戏对象的Transform组件旋转一个小的角度,这样保持这个对象沿着Y轴每秒旋转5°"。

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.

你可以使用我们访问transform成员相同的方式来访问更多不同的组件。你需要使用组件Component菜单来添加组件到游戏对象中。所有组件你都可以通过游戏对象脚本参考页中的列出的变量列表访问到。

For more information about the relationship between GameObjects, Scripts, and Components, please jump ahead to the GameObjects page or Using Components page of this manual.

关于游戏对象、脚本和组件之间的关系的更多信息,请跳转到这本手册里的 游戏对象 页或 使用组件

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 it's easy to do.

到目前为止我们的脚本让立方体Cube保持每秒旋转5度。我们希望它能够每秒旋转不同的角度值。我们可以改变数值并保持。但是之后我们需要等待脚本被重新编译。然后我们还必须进入到播放模式才能够看到结果。现在有一种更快的方式来实现。我们可以在播放模式下实时试验旋转速度,这将会很容易做到。

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:

我们将要声明一个速度speed变量并在函数中使用这个变量,而不是在Rotate()函数中使用5。像下面代码这样修改并保存:

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.

注意这个例子是Javascript的写法。C#的用户需要把var关键字换成int。现在选中立方体Cube观察检视面板。注意看我们的speed变量是如何显示的。

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.

这个变量现在可以在检视面板中直接被修改掉,就像在资源管理器里重命名一个文件一样。选中它,按下退格件修改值。你也可以在数值上右击或Option点击并拖动鼠标向上或向下。你可以再任何时刻改变变量甚至于游戏运行时。

Hit Play and try modifying the speed value. The Cube's rotation speed will change instantly. When you exit Play mode, you'll see that your changes are reverted back to their value before entering Play mode. This way you can play, adjust, and experiment to find the best value, then apply that value permanently.

点击播放按钮并试着修改speed的值。立方体的旋转速度将会立马变化。当你退出播放模式后,你会看到改变的值又恢复到你进入播放模式前的值上。这样你可以播放,调整和测试来找到最佳的值,然后一直使用这个值。

Using this method of changing a variable's value in the Inspector means that you can re-use one script on many objects, each with a different variable value. If you attach the script to multiple Cubes, and change the speed of each cube, they will all rotate at different speeds even though they use the same script.

使用这种方式来改变检视面板里一个变量的值,这就意味着你能够重复使用一个脚本到许多对象上。每一个对象都使用不同的变量值。如果你附加脚本到多个立方体上。然后修改每一个立方体的speed变量,即便他们使用同一个脚本,他们会以不同的速度旋转。

Accessing Other Components 访问其他组件

When writing a script Component, you can access other components on the GameObject from within that script.

当编写一个脚本组件,你可以在这个游戏对象的脚本中访问其他的组件。

Using the GameObject members 使用游戏对象的成员

You can directly access any member of the GameObject class. You can see a list of all the GameObject class members here. If any of the indicated classes are attached to the GameObject as a Component, you can access that Component directly through the script by simply typing the member name. For example, typing transform is equivalent to gameObject.transform. The gameObject is assumed by the compiler, unless you specifically reference a different GameObject.

你可以直接访问游戏对象类中的任何成员。在这里你能够访问到游戏对象类中的全部成员的一个列表。如果任何指定的类作物组件附加到游戏对象,你都可以通过在脚本中简单的输入成员名称来直接访问这个组件。例如,键入transform等价于gameObject.transform。游戏对象是通过编译器来确认的,除非你特别声明一个不同的游戏对象的引用。

Typing this will be accessing the script Component that you are writing. Typing this.gameObject is referring to the GameObject that the script is attached to. You can access the same GameObject by simply typing gameObject. Logically, typing this.transform is the same as typing transform. If you want to access a Component that is not included as a GameObject member, you have to use gameObject.GetComponent() which is explained on the next page.

键入this可以运行你写的脚本访问组件。键入this.gameObject获取对脚本附加的游戏对象的引用。你也可以通过简单键入gameObject来访问这个游戏对象。同理,使用this.transform和输入transform效果一样。如果你想访问一个非游戏对象成员的组件,你需要使用gameObject.GetComponent()关于这个的展开讨论在下一页。

There are many Components that can be directly accessed in any script. For example, if you want to access the Translate function of the Transform component, you can just write transform.Translate() or gameObject.transform.Translate(). This works because all scripts are attached to a GameObject. So when you write transform you are implicitly accessing the Transform Component of the GameObject that is being scripted. To be explicit, you write gameObject.transform. There is no advantage in one method over the other, it's all a matter of preference for the scripter.

很多组件在任何脚本中都能够直接被访问到。例如:你想要访问Transform组件的Translate函数,你可以输入transform.Translate()或者gameObject.transform.Translate()。这样之所有有效是因为所有的脚本被附加到一个游戏对象上。所以当你输入transform你能够隐性访问到被脚本化的游戏对象中的Transform组件。需要明确的是,你要输入gameObject.transform。不存在一种写法比其他写法更有优势,这全凭脚本编写人员的喜好决定。

To see a list of all the Components you can access implicitly, take a look at the GameObject page in the Scripting Reference.

要了解你能够隐性访问的全部组件的列表你可以立刻访问脚本手册里的游戏对象页。

Using GetComponent()
使用GetComponent()

There are many Components which are not referenced directly as members of the GameObject class. So you cannot access them implicitly, you have to access them explicitly. You do this by calling the GetComponent("component name") and storing a reference to the result. This is most common when you want to make a reference to another script attached to the GameObject.

有不少组件没作为游戏对象类的成员被直接引用。所以你不能直接访问到他们,你需要明确的访问他们。你可以调用GetComponent("组件名称")来做这件事并把一个引用存放到结果中。当你想用获取另外一个脚本附属的游戏对象的引用时,这是一种常规做法。

Pretend you are writing Script B and you want to make a reference to Script A, which is attached to the same GameObject. You would have to use GetComponent() to make this reference. In Script B, you would simply write:

假设你现在正在写B脚本这时你想做一个A脚本的引用(该脚本附加到同一游戏对象)。需要使用GetCompnonet()来实现这个引用。在B脚本中,你这样写:

scriptA = GetComponent("ScriptA");

For more help with using GetComponent(), take a look at the GetComponent() Script Reference page.

关于GetComponent()用法的更多帮助,请查阅 脚本参考手册 里 GetComponent()的页面。

Accessing variables in other script Components 访问其他脚本组件中的变量

All scripts attached to your GameObjects are Components. Therefore to get access to a public variable (and methods) in a script you make use of the GetComponent method. For example:

所有被附加到你的游戏对象上的脚本都是组件。因此,你可以在一个脚本中使用GetComponent()的方法来获取对公共变量(和方法)。例如:

function Start () {   // Print the position of the transform component, for the gameObject this script is attached to   Debug.Log(gameObject.GetComponent<Transform>.().position);}

In the previous example the GetComponent<T>. function is used to access the position property of the Transform component. The same technique can be used to access a variable in a custom script Component:

在当前这个例子中GetComponent<T>函数是用来反问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.GetComponent<MyClass>.().speed);}

Accessing a variable defined in C# from Javascript
从Javascript访问C#中定义的变量

To access variables defined in C# scripts the compiled Assembly containing the C# code must exist when the Javascript code is compiled. Unity performs the compilation in different stages as described in the Script Compilation section in the Scripting Reference. If you want to create a Javascript that uses classes or variables from a C# script just place the C# script in the "Standard Assets", "Pro Standard Assets" or "Plugins" folder and the Javascript outside of these folders. The code inside the "Standard Assets", "Pro Standard Assets" or "Plugins" is compiled first and the code outside is compiled in a later step making the Types defined in the compilation step (your C# script) available to later compilation steps (your Javascript script).

要访问C#脚本中定义的变量,那么在Javascript代码被编译之前,编译器中就必须已经存在C#的代码。Unity在不同的阶段执行编译,如在脚本参考Script Compilation部分所述。如果你想创建一个Javascript能够使用一个C#中的类或者变量。请把这个C#脚本放置到"Standard Assets"标准组件,"Pro Standard Assets"专业版标准组件或者"Plugins"插件文件夹中,并把Javascript文件放到这些文件夹以外的其他地方。在"Pro Standard Assets"专业版标准组件或者"Plugins"插件文件夹的代码会先编译,其他地方的代码之后编译。确保你的C#脚本中的定义先被编译好,在下一阶段Javascript脚本编译时已经被定义好了。

In general the code inside the "Standard Assets", "Pro Standard Assets" or "Plugins" folders, regardless of the language (C#, Javascript or Boo), will be compiled first and available to scripts in subsequent compilation steps.

通常在"Pro Standard Assets"专业版标准组件或者"Plugins"插件文件夹中的代码,不管是(C#,Javascript还是Boo),都会先被编译,这样确保后续的编译脚本中能够使用。

Optimizing variable access 优化变量访问

In some circumstances you may be using GetComponent multiple times in your code, or multiple times per frame. Every call to GetComponent does a few extra steps internally to get the reference to the component you require. A more efficient approach is to store the reference to the component for example in your Start() function. As you will be storing the reference and not retrieving directly it is always good practice to check for null references:

有些情况下,你可能会你的代码中多次使用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.GetComponent<MyClass>.();}function Update () {   // Verify that the reference is still valid and print the speed variable   if(myClass != null)      Debug.Log (myClass.speed);}

Static Variables 静态变量

It is also possible to declare variables in your classes as static. There will exist one and only one instance of a static variable for a specific class and it can be modified without the need of an instance of a class object:

在你的类中也可以定义静态变量。这样对于这个特定的类里的静态变量就只会存在一份实例。这个静态变量可以被修改而不需要实例化一个类对象:

(MyClass.js)static public var speed : float = 3.14159;(MyOtherClass.js)function Start () {   Debug.Log (MyClass.speed);}

It is recommended to not use static variables for object references to make sure unused objects are removed from memory.

建议在对象引用中不要使用静态变量以确保未使用的对象能够从内存中删除。

Where to go from here 下一步怎么走

This was just a short introduction on how to use scripts inside the Editor. For more examples, check out the Tutorials that come with Unity. You should also read through Scripting Overview inside the Script Reference, which contains a more thorough introduction into scripting with Unity plus pointers into the reference itself for in-depth information. If you're really stuck, be sure to visit the Unity Answers or Unity Forums and ask questions there. Someone is always willing to help.

这仅仅是对于如何在编辑器中使用脚本的一个简短教程。更多的例子,请参考来自Unity的教程。你也可以通过阅读脚本手册里的 脚本概览,那里面包含了更多Unity脚本的更深层次的介绍。如果你还是没找到的话,请访问 Unity问答Unity论坛,在哪里提问。总有人会愿意帮你解答。

页面最后更新: 2011-10-20

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
u3d快速入门图文教程
Unity3D内部脚本编程入门
Unity3D教程:脚本初级知识(二) | Unity3D教程手册
[Unity 3D] Unity 3D 性能优化(二)
Unity零基础到入门 | Unity中必备组件技能学习!
Unity3D 脚本入门
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服