数组
本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 41 课,共 85 课。
数组可以按顺序存放多个相同类型的值。类型后面要加方括号,值放在花括号中:
int[] scores = { 10, 25, 7 };每个值都有一个索引,表示它在数组中的位置,索引从 0 开始:scores[0]是 10,scores[1]是 25,scores[2]是 7。scores.Length表示值的数量,这里是 3。如果访问scores[3],脚本会因IndexOutOfRangeException而停止,因为数组中没有第四个值。
使用for循环遍历到Length,就能访问数组中的每个值,无论数组里有多少值:
for (int i = 0; i < scores.Length; i++)
{
Debug.Log("Score " + i + ": " + scores[i]);
}如果不需要索引,foreach会更简洁:foreach (int s in scores) { Debug.Log(s); }会按顺序对每个值执行一次。
挑战
中等用数组和循环搭建一排 7 座塔。
- 在
heights的末尾添加6f和2f:{ 2f, 5f, 3f, 1f, 4f, 6f, 2f }。 - 将
PlaceTower那一行替换为for (int i = 0; i < heights.Length; i++)。 - 在循环内部调用
PlaceTower(i * 1.5f - 4.5f, heights[i]);。
按下 开始:七座高度不同的塔会排成一行。然后点击 检查。
亲手试试
using UnityEngine;
public class Skyline : MonoBehaviour
{
void Start()
{
float[] heights = { 2f, 5f, 3f, 1f, 4f };
// 每个高度对应放置一座塔。
PlaceTower(-4.5f, heights[0]);
}
void PlaceTower(float x, float height)
{
GameObject tower = GameObject.CreatePrimitive(PrimitiveType.Cube);
tower.name = "Tower";
tower.transform.position = new Vector3(x, height / 2, 0);
tower.transform.localScale = new Vector3(1, height, 1);
tower.GetComponent<Renderer>().material.color = new Color(0.35f, 0.45f, 0.7f);
}
}
Unity 脚本基础中的所有课
自己练习: Unity 在线编辑器