Wire an AI Studio HUD to Health Events with Unity MCP
After AI Studio exports a Unity HUD prefab, use Cursor + Unity MCP to subscribe health events, refresh the bar and damage text, with a Play-mode checklist and common break-point fixes.
- Unity MCP
- AI Studio
- HUD
- Unity
- Cursor
- AI game development
- tutorial
The HUD is in Unity, the bar looks fine, but combat does not move it—usually the prefab is fine and UI and gameplay do not share the same health events. Design already exported the main HUD as a Canvas / Prefab from VberAI Studio. Gameplay should use Unity MCP in the open project to connect PlayerHealth changes to a Slider / Image.fillAmount, then verify in Play mode.
This post covers only that wiring—not Figma export or MCP install.
| Step | Tool | Output |
|---|---|---|
| HUD structure into the engine | AI Studio | HUD Prefab with stable names |
| Attach scripts, bind refs, edit scene | Cursor (or Claude Code) + Unity MCP | PlayerHealth ↔ HudHealthView |
| Accept | Unity Play | Bar length changes on damage / heal |
Related:
Agree on names before polish
After AI Studio export, code must find the bar via path or serialized refs. Before export (or right after import), keep names stable:
| Role | Suggested name | Notes |
|---|---|---|
| HUD root | HUD_Root | Unique in the scene |
| Health fill | HUD_HealthFill | Image (Filled) or under Slider.fillRect |
| Optional value text | HUD_HealthText | TextMeshProUGUI, e.g. 80/100 |
| Optional damage flash | HUD_DamageFlash | Full-screen or border Image, default transparent |
Avoid design defaults like Rectangle 42 or Group 3—both MCP and hand-written scripts will inherit the mess.
Step 1: Confirm the HUD is in the scene
- Open the player scene (e.g.
Game) - Hierarchy should show
HUD_Root(or your equivalent) with a health Image / Slider under it - Canvas Render Mode and camera setup are correct (Screen Space - Overlay is simplest)
Read-only smoke test via MCP (do not edit the scene):
List GameObjects in the active scene whose names contain HUD, and the UI component types on them. Do not modify anything.
If the list is empty: re-export/sync from AI Studio, or check that the Prefab was dropped into the wrong scene.
Step 2: Gameplay exposes health changes—never Find the UI
Keep health on the player and broadcast with a C# event (or UnityEvent). The HUD only subscribes; it must not drive logic via Find("Player").
Ask Unity MCP from Cursor (paths can match your project):
Create Assets/Scripts/Combat/PlayerHealth.cs:
- maxHealth, currentHealth (float)
- event Action<float,float> OnHealthChanged(current, max)
- TakeDamage(float), Heal(float); clamp to 0..max
- If current<=0 after damage, fire OnHealthChanged again and optionally OnDied
- Attach to the scene Player; broadcast once in Start
Do not modify any HUD nodes.
Reference implementation (generate, then review):
using System;
using UnityEngine;
public class PlayerHealth : MonoBehaviour
{
[SerializeField] float maxHealth = 100f;
float currentHealth;
public event Action<float, float> OnHealthChanged;
public event Action OnDied;
void Awake() => currentHealth = maxHealth;
void Start() => OnHealthChanged?.Invoke(currentHealth, maxHealth);
public void TakeDamage(float amount)
{
if (amount <= 0f || currentHealth <= 0f) return;
currentHealth = Mathf.Max(0f, currentHealth - amount);
OnHealthChanged?.Invoke(currentHealth, maxHealth);
if (currentHealth <= 0f) OnDied?.Invoke();
}
public void Heal(float amount)
{
if (amount <= 0f || currentHealth <= 0f) return;
currentHealth = Mathf.Min(maxHealth, currentHealth + amount);
OnHealthChanged?.Invoke(currentHealth, maxHealth);
}
}
Temporary damage key for wiring (delete later):
Add temporary DebugDealDamage.cs on Player: pressing H deals 10 damage to PlayerHealth on the same object. Wiring acceptance only.
Step 3: HUD view only listens and updates the bar
Add a view script with serialized references. Do not GameObject.Find every frame in Update.
Create Assets/Scripts/UI/HudHealthView.cs:
- Serialize Image healthFill (Filled, Horizontal)
- Optional TMP_Text healthText
- Serialize PlayerHealth playerHealth (or resolve the unique PlayerHealth at Awake)
- OnEnable subscribe OnHealthChanged; OnDisable unsubscribe
- In the callback: healthFill.fillAmount = current/max; text $"{current:0}/{max:0}"
- Attach to HUD_Root; assign HUD_HealthFill Image to healthFill
- Assign Player's PlayerHealth to playerHealth
Reference:
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class HudHealthView : MonoBehaviour
{
[SerializeField] PlayerHealth playerHealth;
[SerializeField] Image healthFill;
[SerializeField] TMP_Text healthText;
void OnEnable()
{
if (playerHealth == null) return;
playerHealth.OnHealthChanged += HandleHealthChanged;
// If you subscribe after Start, pull once; here we rely on PlayerHealth.Start
}
void OnDisable()
{
if (playerHealth == null) return;
playerHealth.OnHealthChanged -= HandleHealthChanged;
}
void HandleHealthChanged(float current, float max)
{
float t = max > 0f ? current / max : 0f;
if (healthFill != null) healthFill.fillAmount = t;
if (healthText != null) healthText.text = $"{Mathf.CeilToInt(current)}/{Mathf.CeilToInt(max)}";
}
}
If the Image is not Filled: have MCP set Image Type = Filled, Fill Method = Horizontal, then bind fillAmount. With a Slider, write slider.value = t (minValue=0, maxValue=1)—same pattern.
Step 4: Let Unity MCP fill serialized refs
After compile, be explicit in Cursor:
In the active scene:
1. Confirm Player has PlayerHealth; HUD_Root has HudHealthView
2. Point HudHealthView.healthFill at the Image named HUD_HealthFill
3. Point HudHealthView.playerHealth at Player's PlayerHealth
4. If HUD_HealthText exists, assign the TMP_Text
5. Save the scene
Then list any remaining None serialized fields on those two components.
Read-only check:
Inspect HudHealthView and PlayerHealth references: any missing scripts or None fields? Report only—do not edit the scene.
Step 5: Play acceptance checklist
Enter Play and tick all of these before calling wiring done:
- On enter: bar is full (or matches
current/max), not empty/stale - Press H (or hit the player):
fillAmountdrops; text updates if present - Damage to 0: bar empty; death state stable; HUD does not thrash
- Heal: bar rises (temp key or pickup)
- Exit Play and re-enter: refs still valid; no Missing Script
Acceptance prompt:
I am accepting HUD wiring in Play mode. If Console shows NullReferenceException, say whether it is PlayerHealth or HudHealthView and which serialized field is None. Diagnose first, propose the minimal fix, wait for my OK before editing.
Common break points
| Symptom | Check first |
|---|---|
| Bar never moves in Play | OnHealthChanged not subscribed; or damage never hits TakeDamage |
| NRE on Play enter | healthFill / playerHealth still None |
| Bar inverted or jumps | Image not Filled; wrong Rect used as fill |
| Text stuck | Wrong TMP; missing font asset errors on the component |
| AI edits the wrong objects | Prompt: “Only touch HUD_Root / Player; do not move level geometry” |
Rule: gameplay changes health; UI only listens. Do not Find("HUD_HealthFill") inside PlayerCombat—the next AI Studio re-export rename will break combat too.
Living with HUD re-exports
When design re-exports from AI Studio:
- Keep
HUD_HealthFill/HUD_Rootnames when possible - After re-import, only re-run step 4 reference checks—do not let MCP rewrite
PlayerHealth - Keep the view script in the project; rebind if Prefab variant refs were cleared
One-line boundary prompt:
This pass only fixes lost UI Prefab references. Do not change any gameplay scripts under Assets/Scripts/Combat.
Summary
- AI Studio delivers HUD structure into Unity
PlayerHealthbroadcasts(current, max)HudHealthViewsubscribes and updatesfillAmount/ text- Unity MCP attaches components, fills serialized refs, applies minimal Console fixes
- Accept with a damage key + Play checklist—not “script generated successfully”
That closes a repeatable loop: UI into engine → event wiring → Play accept. Bags, mana bars, and boss bars can copy the same pattern.
Keep reading
More guides you might like
Game UI Design: Traditional Workflow vs AI Art + VberAI Studio In-Place Split
Compare PS/Figma hand slicing with VberAI Studio: import or AI-generate UI, auto split layers, export layered PSD or image sets. Effects, steps, and demo videos.
- game-ui-design
- game-ui-designer-flow
- ui-slicing
- AIGC
Free Background Removal in VberAI: Glow / VFX / Semi-Transparent Cutouts with PNG + Alpha
VberAI AI Super Matting has three modes: free matting for solid-color and game glow FX, AI background removal for complex scenes up to 4096×4096, and Super AI matting for hair, semi-transparent edges, and shadows—with transparent PNG plus Alpha.
- vberai
- ai-super-matting
- matting
- super-matting
Build a 3D RPG with Unity MCP: Third-Person Control, Combat, and Quests
A practical Unity MCP walkthrough for a playable 3D RPG prototype—third-person movement, real-time melee, enemy state machines, and quest wiring in Cursor or other MCP AI IDEs. Polish UI later when you need it.
- Unity MCP
- 3D RPG
- Unity
- combat