---
tags:
    - "Loop"
    - "For"
    - "Each"
    - "List"
    - "Iterate"
    - "Foreach"
    - "While"
---

# Foreach

[Control](index.md) / **Foreach**

## Description

Loops a game object collection and runs the Instructions for each entry

## Parameters

| Name | Description |
| :--- | :---------- |
| Text | The text to print |

## Code

```cs
using System;
using System.Collections.Generic;
using UnityEngine;
using VisualScript.Icons;

namespace VisualScript.Runtime
{
    [Title("Foreach")]
    [Image(typeof(IconLoop), ColorTheme.Type.Blue)]
    
    [Description("Loops a game object collection and runs the Instructions for each entry")]
    [Category("Control/Foreach")]
    
    [Parameter("Text", "The text to print")]
    
    [Keywords("Loop", "For", "Each", "List", "Iterate", "Foreach", "While")]
    
    [NestOuterList(nameof(m_Instructions))]
    
    [Serializable]
    public class InstructionCoreLoopForeach : Instruction
    {
        [SerializeField]
        private GetCollectionGameObjects m_Collection = new GetCollectionGameObjects();
        
        [SerializeField] private Instructions m_Instructions = new Instructions();
        
        [NonSerialized] 
        private List<GameObject> m_CacheValues = new List<GameObject>();

        protected override string GetTitle(GameObject source) => $"Foreach {this.m_Collection} run {this.m_Instructions}";

        protected override async Awaitable Run(Args args)
        {
            this.m_Collection.Get(args, this.m_CacheValues);
            foreach (GameObject target in this.m_CacheValues)
            {
                using Args iterationArgs = Args.Get(args.Source, target);
                await this.m_Instructions.Run(iterationArgs, this.ParentCancelToken);
            }
        }
        
        public override void OnCancel()
        {
            base.OnCancel();
            this.m_Instructions.Cancel();
        }
    }
}
```

