> For the complete documentation index, see [llms.txt](https://weichihlin.gitbook.io/unity/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://weichihlin.gitbook.io/unity/for-loop-c.md).

# For Loop (C#)

## 迴圈基礎

### 範例程式

{% embed url="<https://1drv.ms/u/s!AjMRvW84HYeNgawEFKotORH1_mNlVw?e=7PY5uJ>" %}

```csharp
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public GameObject SpherePrefab;

    void Start()
    {
        float length = 1.5f;
        int count = 5;

        for (int j = 0; j < count; j++)
        {
            for (int i = 0; i < count; i++)
            {
                GameObject go = Instantiate(SpherePrefab);
                go.transform.position = new Vector3(i * length - count / 2 * length,0 ,j * length - count / 2 * length);
            }
        }
    }
}

```

### 執行結果ˇ

<figure><img src="/files/VrzlhIAZ8HyEzMGXUhXA" alt=""><figcaption></figcaption></figure>

## 迴圈謎題練習

<figure><img src="/files/eFgW7jfk18sqQc8zX2SL" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
試著修改劃紅線的程式碼，去解以下題目。
{% endhint %}

### 題目1<br>

<figure><img src="/files/149pSJ6FODVMPnOgJ817" alt=""><figcaption></figcaption></figure>

### 參考答案

```csharp
using UnityEngine;

public class GameManager : MonoBehaviour
{
    public GameObject SpherePrefab;

    void Start()
    {
        float length = 1.5f;
        int count = 5;

        for (int j = 0; j < count; j++)
        {
            for (int i = 0; i <= j; i++)
            {
                GameObject go = Instantiate(SpherePrefab);
                go.transform.position = new Vector3(i * length - count / 2 * length,0 ,j * length - count / 2 * length);
            }
        }
    }
}
```

### 題目2

<figure><img src="/files/Hn9VmOPszbTaZpvYoD7x" alt=""><figcaption></figcaption></figure>

### 題目3

<figure><img src="/files/IIv1J0SQnNjRIxFymo9F" alt=""><figcaption></figcaption></figure>

### 題目4

<figure><img src="/files/LJOWyaFrJG9K4TyoZIY9" alt=""><figcaption></figcaption></figure>
