Logo
Section 1 / 7

Unity 脚本入门

了解在 Unity 中为何需要脚本编程。

导入

Unity 脚本入门

了解在 Unity 中为何需要脚本编程。

No configuration found for ID: 30d621a3794e5207deb3fd601ac0d0792d46301502e2acfdfbd9b133269d58ad

1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class InputMover : MonoBehaviour 6{ 7 private void Update() 8 { 9 Vector3 pos = transform.position; 10 pos.x += Input.GetAxis("Horizontal") * Time.deltaTime * 20; 11 transform.position = pos; 12 } 13}

Update 方法(我们将在后续课程中更详细地讨论这类事件方法)在每一帧渲染之前被调用,而 Time.deltaTime 提供了自上一帧以来经过的时间。因此,将移动逻辑编写在 Update 方法中,意味着我们每帧都会更新附加的游戏对象的位置。

具体实现时,我们先将上一帧游戏对象的位置存储在 pos 变量中。接着,将其增加 Time.deltaTime 与 20 的乘积,再乘以一个介于 -1 到 +1 之间的值(因为 Input.GetAxis("Horizontal") 返回的值在这个范围内:右箭头键为 +1,左箭头键为 -1)。最后,我们将 pos 中存储的新位置赋给游戏对象。

具体实现时,我们先将上一帧游戏对象的位置存储在 `pos` 变量中。接着,将其增加 `Time.deltaTime` 与 `20` 的乘积,再乘以一个介于 `-1` 到 `+1` 之间的值(因为 `Input.GetAxis("Horizontal")` 返回的值在这个范围内:右箭头键为 `+1`,左箭头键为 `-1`)。最后,我们将 `pos` 中存储的新位置赋给游戏对象。

No configuration found for ID: 7b0ce0b17ae592abe067a4aa32666ad93c7270cfa08972e11bd294d45326afbb

1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class SoundPlayer : MonoBehaviour 6{ 7 public AudioSource HitSound; 8 9 private void OnCollisionEnter(Collision collision) 10 { 11 HitSound.Play(); 12 } 13}

OnCollisionEnter 方法在附加的游戏对象检测到碰撞时被触发。因此,我们只需对 HitSound 这个 AudioSource 变量调用 Play 方法即可。

`OnCollisionEnter` 方法在附加的游戏对象检测到碰撞时被触发。因此,我们只需对 `HitSound` 这个 `AudioSource` 变量调用 `Play` 方法即可。

No configuration found for ID: f18c877f4e1ff669bd11acfd53e8e05d26200eba4ff396f0f88dcffd716a606b

1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class CubeSpawner : MonoBehaviour 6{ 7 void Start() 8 { 9 StartCoroutine(SpawnCube()); 10 } 11 12 IEnumerator SpawnCube() 13 { 14 for (int j = 9; j >= -1; j -= 2) 15 { 16 for (int i = -11; i <= 11; i += 2) 17 { 18 GameObject Cube = GameObject.CreatePrimitive(PrimitiveType.Cube); 19 Cube.transform.position = new Vector3(i, j, 0); 20 yield return new WaitForSeconds(.1f); 21 } 22 } 23 } 24}

SpawnCube 方法是一个 C# 协程,它是一种可以使用 yield 暂停执行的方法(类似于 JavaScript 中的生成器函数)。两个 for 循环共执行 第18至20行 的代码 72 次,其中 i 和 j 的值分别对应世界空间中立方体的 x 坐标和 y 坐标。

在每次循环中,创建一个新的立方体游戏对象并存储在 Cube 变量中,然后根据 i 和 j 的值设置其位置。最后,通过 yield return new WaitForSeconds(0.1f) 暂停 0.1 秒,使下一次迭代延迟执行。

`SpawnCube` 方法是一个 C# 协程,它是一种可以使用 `yield` 暂停执行的方法(类似于 JavaScript 中的生成器函数)。两个 `for` 循环共执行 第18至20行 的代码 72 次,其中 `i` 和 `j` 的值分别对应世界空间中立方体的 x 坐标和 y 坐标。

在每次循环中,创建一个新的立方体游戏对象并存储在 `Cube` 变量中,然后根据 `i` 和 `j` 的值设置其位置。最后,通过 `yield return new WaitForSeconds(0.1f)` 暂停 0.1 秒,使下一次迭代延迟执行。

No configuration found for ID: ad33b0ae9f5d08301787e96195e0dcf40eca3a5793dbb598834fc9186b1f5dfe

Unity 3D 核心概念:物理

基本概念