> For the complete documentation index, see [llms.txt](https://niam.gitbook.io/documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://niam.gitbook.io/documentation/game-creator-2/inline-variables/iterating-list.md).

# Iterating List

Inline List Variables are useful when you need to work with multiple values during an instruction flow.

A common operation is to **iterate** over those values: take each item in the list, run some instructions, and then continue with the next item.

For example:

```
Enemies
    ↓
For Each
    ├─ Enemy A → Apply Damage
    ├─ Enemy B → Apply Damage
    └─ Enemy C → Apply Damage
```

Game Creator provides several ways to work with list values. For Inline Variables, the **For Each** instruction is usually the simplest and most flexible approach.

## Choosing an Iteration Method

The best method depends on what you are trying to do:

| Method               | Best for                                 | Limitations                                                                  |
| -------------------- | ---------------------------------------- | ---------------------------------------------------------------------------- |
| **Loop List**        | Iterating Game Objects with an Action    | Only supports Game Object values and requires an additional Action component |
| **Indexer Variable** | Accessing a specific element by index    | Requires a Local Name Variable component                                     |
| **For Each**         | Running instructions once for every item | General-purpose iteration                                                    |

If you simply need to **run some instructions for every item in a collection**, use **For Each**.

## Using For Each

The **For Each** instruction evaluates a collection and executes its instruction block once for every item.

For example, suppose a Value List produces three enemies:

```
[Enemy A, Enemy B, Enemy C]
```

A For Each instruction processes them in sequence:

```
Enemy A → Instruction Block
Enemy B → Instruction Block
Enemy C → Instruction Block
```

#### The Current Item

Inside the For Each instruction, the current element is available through an Inline Name Variable named:

```
value
```

The type of `value` is determined by the type of the collection being iterated.

For example, if the collection contains Game Objects:

```
value → GameObject
```

If it contains numbers:

```
value → Number
```

If it contains strings:

```
value → String
```

This means the same For Each instruction can be used with different kinds of data without creating a separate Local Variable just to hold the current item.

#### Example

Suppose a Value List returns all enemies within a certain area.

You can use:

```
For Each
│
├─ value = Enemy A
│   └─ Apply Damage to value
│
├─ value = Enemy B
│   └─ Apply Damage to value
│
└─ value = Enemy C
    └─ Apply Damage to value
```

The `value` variable changes for each iteration.

You don't need to create or reset a separate variable for it.

## Nested Iteration

For Each instructions can be placed inside other control-flow scopes.

For example:

```
For Each Enemy
│
├─ value = Enemy A
│
└─ For Each Effect
    │
    ├─ value = Effect 1
    └─ value = Effect 2
```

Each iteration creates the appropriate nested scope.

Because Inline Variables use scoped execution contexts, an inner variable can temporarily shadow an outer variable with the same name.

> **Tip:** If you have nested loops, pay attention to which `value` is currently in scope. The innermost `value` is the one resolved by instructions inside that scope.

## Value Lists

A **Value List** is a data source that produces a collection of values at runtime.

Value Lists can be used in two places:

1. As the source for an **Inline List Variable**.
2. Directly as the collection being processed by **For Each**.

This allows a list to be generated when the instruction executes rather than requiring a permanently stored list.

For example:

```
Physics Query
      ↓
Value List
      ↓
For Each
      ↓
Current value
```

The actual collection does not have to exist as a persistent variable.

### Available Value List Sources

Value Lists are grouped into several categories:

* [Characters](https://chatgpt.com/documentation/game-creator-2/inline-variables/iterating-list/characters.md)
* [Constant](https://chatgpt.com/documentation/game-creator-2/inline-variables/iterating-list/constant.md)
* [Inventory](https://chatgpt.com/documentation/game-creator-2/inline-variables/iterating-list/inventory.md)
* [Physics 3D](https://chatgpt.com/documentation/game-creator-2/inline-variables/iterating-list/physics-3d.md)
* [Quests](https://chatgpt.com/documentation/game-creator-2/inline-variables/iterating-list/quests.md)
* [Stats](https://chatgpt.com/documentation/game-creator-2/inline-variables/iterating-list/stats.md)
* [Transform](https://chatgpt.com/documentation/game-creator-2/inline-variables/iterating-list/transform.md)
* [Variables](https://chatgpt.com/documentation/game-creator-2/inline-variables/iterating-list/variables.md)

Each category provides different ways of producing a collection.

For example, Physics 3D Value Lists can produce objects found by a physics query, while Transform Value Lists can produce objects related to a hierarchy.

See the individual category pages for the available sources and their configuration options.

## Value List vs Inline List Variable

These two concepts are related, but they serve different purposes.

### Value List

A Value List is a **source of values**.

It answers:

> "Where should these values come from?"

The list can be generated dynamically when it is evaluated.

### Inline List Variable

An Inline List Variable is **temporary storage** for a collection.

It answers:

> "Where should I keep this collection while I work with it?"

For example:

```
Value List
   │
   │ produces
   ▼
[Enemy A, Enemy B, Enemy C]
   │
   ▼
Inline List Variable: Targets
```

You can then manipulate `Targets` using list instructions.

You can also skip the Inline List Variable entirely when you only need to process the values once:

```
Value List
   ↓
For Each
   ↓
Process value
```

### Which Should I Use?

Use a **Value List directly with For Each** when:

* You only need to process each value once.
* You don't need to modify or retain the collection.
* The collection can be generated when the instruction runs.

Use an **Inline List Variable** when:

* You need to keep the collection for multiple instructions.
* You need to modify the list.
* You need to access the list by index.
* You need to perform several operations on the same collection.

## Custom Value Lists

The built-in Value Lists cover common Game Creator use cases, but you can also create your own data sources.

To create a custom Value List, create a class that inherits from `TValueList`:

```csharp
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;
using GameCreator.Runtime.Common;
using GameCreator.Runtime.Variables;
using Niam.Runtime.InlineVariables;

namespace YourNamespace
{
    [Title("My Custom Source")]
    [Category("Custom/My Custom Source")]
    [Description("A custom list of values from your system")]
    [Image(typeof(IconComponent), ColorTheme.Type.Blue)]
    [Serializable]
    public class ValueListMyCustomSource : TValueList
    {
        [SerializeField]
        private PropertyGetGameObject m_Source =
            GetGameObjectSelf.Create();

        public override IdString TypeID =>
            ValueGameObject.TYPE_ID;

        public override PooledObject<List<object>> GetPooledList(
            out List<object> list)
        {
            var pool = ListPool<object>.Get(out list);

            GameObject source = m_Source.Get(m_Args);

            if (source != null)
            {
                var components =
                    source.GetComponentsInChildren<Renderer>();

                foreach (var renderer in components)
                {
                    list.Add(renderer.gameObject);
                }
            }

            return pool;
        }

        public override void Foreach(
            Action<TValueList, object> visitor)
        {
            if (visitor == null) return;

            using var pool = GetPooledList(out var list);

            foreach (var item in list)
            {
                visitor(this, item);
            }
        }

        public override void FillList(List<object> list)
        {
            if (list == null) return;

            list.Clear();

            using var pool = GetPooledList(out var source);
            list.AddRange(source);
        }

        public override string ToString() =>
            $"My Custom Source from {m_Source}";
    }
}
```

#### Implementing a Custom Value List

There are three important parts to a custom implementation.

**1. Inherit from `TValueList`**

Your class must derive from:

```csharp
TValueList
```

This makes it available to the Inline Variables Value List system.

**2. Declare the Element Type**

`TypeID` tells Inline Variables what type of value the collection contains.

For example:

```csharp
public override IdString TypeID =>
    ValueGameObject.TYPE_ID;
```

This declares that the list contains Game Objects.

The type must match the objects that your implementation adds to the list.

**3. Provide the Values**

`GetPooledList` is the primary data-access method.

It should populate the supplied list with the values produced by your source and return the associated pool object.

Using `ListPool<object>` is recommended because Value Lists can be evaluated frequently during gameplay and temporary allocations should be minimized.

### Optional Methods

`Foreach` and `FillList` provide additional ways to consume the values.

#### `Foreach`

`Foreach` supports visitor-style iteration:

```csharp
public override void Foreach(
    Action<TValueList, object> visitor)
```

Use this when the caller can process values one at a time without requiring a separate list.

#### `FillList`

`FillList` copies the generated values into a caller-provided list:

```csharp
public override void FillList(List<object> list)
```

This is useful when the caller needs normal list access rather than the pooled list returned by `GetPooledList`.

If you don't need specialized behavior, the implementations shown above are sufficient.

### GC2 Attributes

GC2 uses attributes to describe the Value List in the editor.

| Attribute                   | Purpose                          |
| --------------------------- | -------------------------------- |
| `[Title("...")]`            | Display name shown in the picker |
| `[Category("...")]`         | Folder/category in the picker    |
| `[Description("...")]`      | Tooltip or descriptive text      |
| `[Image(...)]`              | Icon displayed in the inspector  |
| `[Parameter("...", "...")]` | Documents a serialized field     |

For example:

```csharp
[Title("My Custom Source")]
[Category("Custom/My Custom Source")]
[Description("A custom list of values from your system")]
[Image(typeof(IconComponent), ColorTheme.Type.Blue)]
```

These attributes control how your custom Value List appears in the Game Creator editor.

## Automatic Discovery

Custom Value Lists do not require manual registration.

GC2 discovers classes derived from `TValueList` through reflection, provided that:

1. The class is in an assembly that references `Niam.Runtime.InlineVariables`.
2. The class has the `[Serializable]` attribute.
3. The class is not `abstract`.

Once Unity recompiles the assembly, the Value List should become available through the appropriate picker.

## Summary

The simplest way to think about list iteration is:

```
Value List
   ↓
produces values
   ↓
For Each
   ↓
value
   ↓
run instructions
   ↓
next value
```

Use **For Each** when you want to perform an operation for every item.

Use a **Value List** when you need to define where the items come from.

Use an **Inline List Variable** when you need temporary storage for the collection itself.

Together, these allow you to build list-processing logic without creating persistent variables solely for intermediate data.
