# 6. Ability Bar UI and Input
Part of [[Ability System]]. Previous: [[5. Data-Driven Abilities with ScriptableObjects]]. Next: [[7. Ability Tests Balancing and Pitfalls]].
> [!warning] Code not compiled in Unity
> C# type-checked against 6000.5.8f1 and its Input System assembly. The UXML and USS weren't validated by any tool. Nothing was run.
## 6.1 Input
1. In your Input Actions asset, add a `Gameplay` map with actions `Ability1`, `Ability2`, `Ability3` (Button: keys 1/2/3, gamepad West/North/East) and `CancelCast` (Escape / gamepad B). See [[Input System]].
2. Add **AbilityInput** to the player. Fill the slots with the action references and abilities.
```csharp
// Assets/Scripts/Abilities/AbilityInput.cs
using System;
using UnityEngine;
using UnityEngine.InputSystem;
/// <summary>Binds Input System actions to ability slots. One InputActionReference per slot.</summary>
[RequireComponent(typeof(AbilityUser))]
public sealed class AbilityInput : MonoBehaviour
{
[Serializable]
public struct Slot
{
public InputActionReference action;
public AbilityDefinition ability;
}
[SerializeField] Slot[] slots;
[SerializeField] InputActionReference cancelCast;
AbilityUser _user;
Action<InputAction.CallbackContext>[] _handlers;
void Awake() => _user = GetComponent<AbilityUser>();
void OnEnable()
{
_handlers = new Action<InputAction.CallbackContext>[slots.Length];
for (var i = 0; i < slots.Length; i++)
{
var slot = slots[i];
if (slot.action == null || slot.ability == null)
continue;
_handlers[i] = _ => _user.TryActivate(slot.ability.id);
slot.action.action.performed += _handlers[i];
slot.action.action.Enable();
}
if (cancelCast != null)
{
cancelCast.action.performed += OnCancel;
cancelCast.action.Enable();
}
}
void OnDisable()
{
for (var i = 0; i < slots.Length; i++)
{
if (_handlers != null && _handlers[i] != null && slots[i].action != null)
slots[i].action.action.performed -= _handlers[i];
}
if (cancelCast != null)
cancelCast.action.performed -= OnCancel;
}
void OnCancel(InputAction.CallbackContext _) => _user.Caster.Interrupt();
}
```
Each slot captures its own `slot` copy in the lambda, and the handlers are stored so `OnDisable` can unsubscribe exactly what `OnEnable` added. Forgetting that leaks handlers every time the player respawns.
## 6.2 The bar
UXML (`Assets/UI/AbilityBar.uxml`):
```xml
<ui:UXML xmlns:ui="UnityEngine.UIElements">
<Style src="AbilityBar.uss" />
<ui:VisualElement name="ability-bar" class="ability-bar">
<ui:VisualElement name="slot-0" class="slot">
<ui:VisualElement name="icon" class="icon" />
<ui:VisualElement name="cooldown-mask" class="cooldown-mask" />
<ui:Label name="seconds" class="seconds" />
<ui:Label name="charges" class="charges" />
<ui:Label text="1" class="key" />
</ui:VisualElement>
<ui:VisualElement name="slot-1" class="slot">
<ui:VisualElement name="icon" class="icon" />
<ui:VisualElement name="cooldown-mask" class="cooldown-mask" />
<ui:Label name="seconds" class="seconds" />
<ui:Label name="charges" class="charges" />
<ui:Label text="2" class="key" />
</ui:VisualElement>
<ui:VisualElement name="slot-2" class="slot">
<ui:VisualElement name="icon" class="icon" />
<ui:VisualElement name="cooldown-mask" class="cooldown-mask" />
<ui:Label name="seconds" class="seconds" />
<ui:Label name="charges" class="charges" />
<ui:Label text="3" class="key" />
</ui:VisualElement>
</ui:VisualElement>
<ui:VisualElement name="cast-bar" class="cast-bar hidden">
<ui:VisualElement name="fill" class="fill" />
</ui:VisualElement>
</ui:UXML>
```
USS (`Assets/UI/AbilityBar.uss`):
```css
.ability-bar { position: absolute; bottom: 24px; left: 0; right: 0; flex-direction: row; justify-content: center; }
.slot { width: 72px; height: 72px; margin: 0 6px; border-radius: 8px; overflow: hidden;
background-color: rgba(0,0,0,0.6); border-width: 2px; border-color: rgba(255,255,255,0.3);
translate: 0 0; transition-property: translate, border-color; transition-duration: 0.06s, 0.15s; }
.icon { position: absolute; left: 0; top: 0; right: 0; bottom: 0; -unity-background-scale-mode: scale-to-fit; }
.cooldown-mask { position: absolute; left: 0; right: 0; bottom: 0; height: 0%; background-color: rgba(0,0,0,0.65); }
.seconds { position: absolute; left: 0; right: 0; top: 22px; -unity-text-align: middle-center; font-size: 22px; color: white; }
.charges { position: absolute; right: 4px; bottom: 2px; font-size: 14px; color: rgb(255,230,120); }
.key { position: absolute; left: 4px; top: 2px; font-size: 12px; color: rgba(255,255,255,0.7); }
.slot.unaffordable .icon { -unity-background-image-tint-color: rgb(90,110,200); }
.slot.blocked { border-color: rgb(220,60,60); }
.slot.denied { translate: 6px 0; border-color: rgb(255,80,80); }
.cast-bar { position: absolute; bottom: 110px; left: 35%; right: 35%; height: 10px; background-color: rgba(0,0,0,0.6); border-radius: 5px; }
.cast-bar.hidden { display: none; }
.cast-bar .fill { height: 100%; width: 0%; background-color: rgb(255,200,80); border-radius: 5px; }
```
The cooldown mask shrinks from the top as the charge recharges. It's a "vertical wipe", which reads like a radial at a glance and needs no custom mesh. For a true radial, draw an arc with `generateVisualContent` and `Painter2D.Arc`; that's beyond this note.
```csharp
// Assets/Scripts/Abilities/AbilityBarView.cs
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
/// <summary>
/// UI Toolkit ability bar: one slot per ability with an icon, a cooldown mask that shrinks
/// as the charge recharges, a seconds label, a charge count, and a cast bar.
/// Expects the UXML in the note (elements named "slot-0".."slot-N" and "cast-bar").
/// </summary>
[RequireComponent(typeof(PanelRenderer))]
public sealed class AbilityBarView : MonoBehaviour
{
[SerializeField] AbilityUser user;
[SerializeField] AbilityDefinition[] slotAbilities;
PanelRenderer _panel;
PanelRenderer.VersionedUIReloadCallback _reload;
readonly List<SlotView> _slots = new List<SlotView>();
VisualElement _castBar;
VisualElement _castFill;
sealed class SlotView
{
public AbilityDefinition Ability;
public VisualElement Root;
public VisualElement Mask;
public Label Seconds;
public Label Charges;
}
void OnEnable()
{
_panel = GetComponent<PanelRenderer>();
_reload = OnUIReload;
_panel.RegisterUIReloadCallback(_reload);
if (user != null)
user.ActivationAttempted += OnAttempt;
}
void OnDisable()
{
if (_panel != null && _reload != null)
_panel.UnregisterUIReloadCallback(_reload);
if (user != null)
user.ActivationAttempted -= OnAttempt;
}
void OnUIReload(PanelRenderer renderer, VisualElement root, int version)
{
_slots.Clear();
if (root == null)
return;
for (var i = 0; i < slotAbilities.Length; i++)
{
var el = root.Q("slot-" + i);
if (el == null)
continue;
var view = new SlotView
{
Ability = slotAbilities[i],
Root = el,
Mask = el.Q("cooldown-mask"),
Seconds = el.Q<Label>("seconds"),
Charges = el.Q<Label>("charges")
};
var icon = el.Q("icon");
if (icon != null && view.Ability != null && view.Ability.icon != null)
icon.style.backgroundImage = new StyleBackground(view.Ability.icon);
_slots.Add(view);
}
_castBar = root.Q("cast-bar");
_castFill = _castBar?.Q("fill");
}
void LateUpdate()
{
if (user == null || user.Caster == null)
return;
var now = Time.timeAsDouble;
var caster = user.Caster;
foreach (var s in _slots)
{
if (s.Ability == null || !caster.Has(s.Ability.id))
continue;
var cd = caster.Cooldowns;
var charges = cd.Charges(s.Ability.id, now);
var remaining = cd.Remaining(s.Ability.id, now);
var gcd = s.Ability.triggersGlobalCooldown ? cd.GlobalRemaining(now) : 0;
var showRemaining = charges > 0 ? gcd : System.Math.Max(remaining, gcd);
var progress = charges > 0 ? (gcd > 0 ? 1f - (float)(gcd / System.Math.Max(0.001, caster.GlobalCooldown)) : 1f)
: cd.RechargeProgress(s.Ability.id, now);
if (s.Mask != null)
s.Mask.style.height = Length.Percent((1f - progress) * 100f);
if (s.Seconds != null)
s.Seconds.text = showRemaining > 0.05 ? (showRemaining >= 1 ? ((int)System.Math.Ceiling(showRemaining)).ToString() : showRemaining.ToString("0.0")) : string.Empty;
if (s.Charges != null)
s.Charges.text = s.Ability.charges > 1 ? charges.ToString() : string.Empty;
var pool = caster.Resource(s.Ability.resourceId);
s.Root.EnableInClassList("unaffordable", pool != null && !pool.CanAfford(s.Ability.cost));
s.Root.EnableInClassList("blocked", user.Statuses.HasAnyTag(s.Ability.blockedByTags));
}
if (_castBar != null)
{
_castBar.EnableInClassList("hidden", !caster.IsCasting);
if (_castFill != null)
_castFill.style.width = Length.Percent(caster.CastProgress(now) * 100f);
}
}
void OnAttempt(AbilityDefinition def, CastResult result)
{
if (result == CastResult.Completed || result == CastResult.Started)
return;
foreach (var s in _slots)
{
if (s.Ability != def)
continue;
// Restart the "denied" shake: remove, then add next frame so the USS transition replays.
s.Root.RemoveFromClassList("denied");
s.Root.schedule.Execute(() => s.Root.AddToClassList("denied"));
s.Root.schedule.Execute(() => s.Root.RemoveFromClassList("denied")).ExecuteLater(150);
}
}
}
```
### Set it up
1. Create a GameObject called `AbilityBar` with **PanelRenderer** (set its UXML to `AbilityBar.uxml`) and **AbilityBarView**. Assign the player's `AbilityUser` and the same three abilities in slot order.
2. Press Play and cast Fireball. The cast bar fills over 1.5 s, the slot darkens, and the seconds count down from 5. During the 1 s GCD, the other GCD abilities show a brief mask too. Blink (off-GCD) doesn't.
3. Spam Fireball while it's on cooldown. The slot shakes red. That's the `denied` class being re-added through `schedule.Execute` so the transition replays each time.
### Display rules worth copying
- **With charges left,** show only the GCD on the mask. The ability *is* usable once the GCD ends, so a full cooldown mask would lie.
- **Seconds:** whole numbers above 1 s, one decimal below. No text when ready.
- **Colour for state, not text:** blue tint = can't afford, red border = blocked by a status. Reuse the same colours as the status VFX (part 1).
- For more juice (a pop when a cooldown finishes, a flash on gaining a charge), see [[Tweening and UI Juice]]. The same `PanelRenderer` reload-callback pattern is used there.