Unity的C#编程教程_43_遍历数组
1. Print Out All Elements Using For Loop
- 如何将数组和循环搭配起来,打印数组中的所有元素
我们可以使用 for 循环:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArrayOverview : MonoBehaviour
{
public string[] names = new string[] { "Magician", "Monk", "Hero", "Demon" };
public int[] level = new int[] { 20, 18, 16, 33 };
public string[] weapons = new string[] { "axe", "hand", "sword", "spear" };
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
for (int id = 0; id < names.Length; id++) // 设定循环,从 0~3(长度为4)
{
Debug.Log("The level of " + names[id] + " is " + level[id] + " and his weapon is " + weapons[id]);
}
}
}
}
- 检索数组中有没有某个名字,有的话打印出对应的信息
用循环搭配判断语句实现:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArrayOverview : MonoBehaviour
{
public string[] names = new string[] { "Magician", "Monk", "Hero", "Demon" };
public int[] level = new int[] { 20, 18, 16, 33 };
public string[] weapons = new string[] { "axe", "hand", "sword", "spear" };
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
for (int id = 0; id < names.Length; id++) // 设定循环,从 0~3(长度为4)
{
if(names[id] == "Hero") // 查询有没有名字叫做 Hero,有的话进行打印信息
{
Debug.Log("The level of " + names[id] + " is " + level[id] + " and his weapon is " + weapons[id]);
}
}
}
}
}
2. Print Out All Elements Using Foreach Loop
- 使用 Foreach 循环遍历数组元素
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArrayOverview : MonoBehaviour
{
public string[] names = new string[] { "Magician", "Monk", "Hero", "Demon" };
public int[] level = new int[] { 20, 18, 16, 33 };
public string[] weapons = new string[] { "axe", "hand", "sword", "spear" };
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
foreach(var item in names) // 这里的 var 表示任意的数据类型
{
Debug.Log(item); // 打印 names 数组中的每一个元素
}
}
}
}
- 查询目标元素并打印
foreach(var item in names)
{
if (item == "Hero") // 是否存在名字 Hero
{
Debug.Log(item); // 有的话进行打印
}
}