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); // 有的話進行列印
}
}