> For AI agents: the complete documentation index is available at /AchUtils/en/llms.txt, the full documentation bundle is available at /AchUtils/en/llms-full.txt.

# ach

﻿# Ach — Shared Variables & Events

A system for sharing values and signals through **ScriptableObject assets**, so components can communicate without referencing each other directly.

> Turn player health into a `PlayerHP` **asset file**, and the health bar UI, hit sound, and game-over manager can all watch the same asset. No inspector wires between them — when the value changes, everything stays in sync automatically.

## Why use it?

```
Conventional approach                 Ach approach
─────────────────────────            ─────────────────────────
UI references Player directly         UI and Player share a PlayerHP asset
Reference breaks across scenes        Asset survives scene changes
Polls player.Hp every frame           Callback only when the value changes
Hard to trace who mutates the value   Event flow is explicit
```

## Five building blocks

| Block          | One-liner                                                       | Example class                  |
| -------------- | --------------------------------------------------------------- | ------------------------------ |
| **Variable**   | An asset holding a single value                                 | `IntVariable`, `FloatVariable` |
| **Event**      | A signal asset carrying a value                                 | `IntEvent`, `VoidEvent`        |
| **Listener**   | Component that turns an event into a UnityEvent                 | `IntEventListener`             |
| **Reference**  | Toggle between a constant and a variable asset in the inspector | `IntReference`                 |
| **Collection** | A runtime-shared list asset                                     | `GameObjectCollection`         |

Built-in types: **Int / Float / Bool / String / Vector2 / Vector3 / Color / GameObject** (plus signal-only **Void**).

## Create assets with right-click

In the Project view, **right-click → Create → AchUtils → Ach**.

```
Create ▸ AchUtils ▸ Ach ▸ Variables    ▸ Int / Float / Bool / String / Vector2 / Vector3 / Color / GameObject Variable
                        ▸ Events       ▸ Void / Int / Float / ... Event
                        ▸ Collections  ▸ GameObject Collection
```

Listeners are components — **Add Component → AchUtils → Ach → Int Event Listener**.

## Quick start

### 1. Variable — share a value as an asset

Create `PlayerHP` via **Create → AchUtils/Ach/Variables/Int Variable**.

```csharp
using AchUtils.Ach;
using UnityEngine;

public class Player : MonoBehaviour
{
    [SerializeField] IntVariable hp;     // drag in the PlayerHP asset

    public void TakeDamage(int amount)
    {
        hp.Value -= amount;              // subscribers are notified automatically
    }
}

public class HealthBar : MonoBehaviour
{
    [SerializeField] IntVariable hp;     // same PlayerHP asset as Player
    [SerializeField] UnityEngine.UI.Slider slider;

    void OnEnable()  => hp.OnChanged += Refresh;   // called only when it changes
    void OnDisable() => hp.OnChanged -= Refresh;

    void Refresh(int value) => slider.value = value;
}
```

`Player` and `HealthBar` know nothing about each other — they connect through the `PlayerHP` asset.

### 2. Event — send a signal

Use a **Void Event** for value-less notifications, or a typed event to carry data.

```csharp
[SerializeField] VoidEvent onPlayerDied;
[SerializeField] IntEvent  onGoldChanged;

void Die()            => onPlayerDied.Raise();
void AddGold(int now) => onGoldChanged.Raise(now);
```

### 3. Listener — wire reactions without code

Add **AchUtils/Ach/Int Event Listener** to the reacting object, then in the inspector drag `onGoldChanged` into `Event` and your method into `Response`. Designers can hook up sounds and effects without writing code.

### 4. Reference — switch between constant and variable

Pick whether a value is a hard-coded constant or a shared variable asset with one checkbox.

```csharp
[SerializeField] FloatReference moveSpeed;   // Use Constant on = constant, off = variable asset

void Update()
{
    transform.position += dir * moveSpeed.Value * Time.deltaTime;
}
```

Prototype fast with constants, then share one variable asset across many places during balancing — **without touching code**.

### 5. Collection — share a runtime list

Create `AliveEnemies` via **Create → AchUtils/Ach/Collections/GameObject Collection**.

```csharp
[SerializeField] GameObjectCollection aliveEnemies;

void OnEnable()  => aliveEnemies.Add(gameObject);
void OnDisable() => aliveEnemies.Remove(gameObject);

// Elsewhere: wave is cleared when no enemies remain
if (aliveEnemies.Count == 0) WaveCleared();
```

## API

### AchVariable\<T>

```csharp
T    Value                          // assigning raises OnChanged if it actually changed
T    InitialValue                   // value applied when play starts
void SetValue(T value)              // ignored if equal
void SetValueAndForceRaise(T value) // raises even if equal
void ResetToInitialValue()

event Action<T>    OnChanged             // (newValue)
event Action<T, T> OnChangedWithHistory  // (oldValue, newValue)
```

### AchEvent\<T> / VoidEvent

```csharp
void Raise(T value)                 // VoidEvent uses Raise()
void Register(Action<T> handler)
void Unregister(Action<T> handler)
T    LastValue                      // last value raised (debug)
```

### AchReference\<T, TVariable>

```csharp
T          Value                    // constant if UseConstant, otherwise the variable's value
bool       UseConstant
T          ConstantValue
TVariable  Variable
// implicit operator T — usable directly as a plain value
```

### AchCollection\<T>

```csharp
int  Count
T    this[int index]
void Add(T item)
bool AddIfMissing(T item)
bool Remove(T item)
bool Contains(T item)
void Clear()

event Action<T> OnAdded
event Action<T> OnRemoved
event Action    OnCleared
```

## Editor conveniences

- **Variable inspector** — shows the live value during play, with a `Reset To Initial Value` button.
- **VoidEvent inspector** — a `Raise` button during play lets you fire the event manually to test listener wiring.
- **Auto reset** — variables and collections revert to their initial/empty state when entering play mode, so every run starts clean even with domain reload disabled.

## Adding a new type

Need a value beyond the built-ins (e.g. `Quaternion`)? Just write one-line subclasses.

```csharp
using UnityEngine;
using AchUtils.Ach;

[CreateAssetMenu(menuName = "AchUtils/Ach/Variables/Quaternion Variable")]
public class QuaternionVariable : AchVariable<Quaternion> { }

[CreateAssetMenu(menuName = "AchUtils/Ach/Events/Quaternion Event")]
public class QuaternionEvent : AchEvent<Quaternion> { }

[System.Serializable]
public class QuaternionUnityEvent : UnityEngine.Events.UnityEvent<Quaternion> { }

public class QuaternionEventListener
    : AchEventListener<Quaternion, QuaternionEvent, QuaternionUnityEvent> { }
```


> **When to use it**
> 
> It shines when you need to share values or signals across scene and prefab boundaries. For a value used only inside a single GameObject, a plain field is simpler.
> 

