Components Working Together
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 4 of 50.
Small components still need each other. A Jetpack needs Fuel on the same object, so it finds the Fuel once in Awake, keeps it in a field, and talks to it through two small public methods:
public class Fuel : MonoBehaviour
{
public float amount = 10f;
public bool IsEmpty()
{
return amount <= 0f;
}
public void Burn(float units)
{
amount = Mathf.Max(amount - units, 0f);
}
}[RequireComponent(typeof(Fuel))]
public class Jetpack : MonoBehaviour
{
public float lift = 4f;
private Fuel fuel;
void Awake()
{
fuel = GetComponent<Fuel>();
}
void Update()
{
if (Keyboard.current.spaceKey.isPressed && !fuel.IsEmpty())
{
fuel.Burn(Time.deltaTime);
transform.position += Vector3.up * lift * Time.deltaTime;
}
}
}[RequireComponent(typeof(Fuel))] makes Unity add a Fuel whenever a Jetpack is added, in the Editor or with AddComponent, and refuses to remove that Fuel while the Jetpack is there. Unity checks it only at the moment the Jetpack is added, so a Jetpack that was already on an object before you wrote the attribute keeps its old setup. Awake is the place to fetch it: it runs once, and the object's own components are all there by then.
The Jetpack never changes amount itself. Fuel decides what burning means, such as never dropping below 0, and the Jetpack only asks. If Fuel later shows a gauge or refills from pickups, the Jetpack does not change.
Challenge
EasyThe skater's dash is free: Space throws her 3 units forward (+z) as often as you press it. Make it cost stamina. The arrows skate her (Mover.cs, ready), and Stamina.cs already refills current by regen per second, up to max (100).
- In Stamina, add a public method
bool TrySpend(float cost). Ifcurrentis at leastcost, it takescostoffcurrentand returnstrue; otherwise it leavescurrentas it is and returnsfalse. - Make Dash need a Stamina on its object, so Unity adds one whenever a Dash is added. Fetch it once, in Awake, into a field.
- A dash costs
cost(the Inspector sets 40). Space dashes only when TrySpend agrees, and otherwise logsToo tired.
Press Play and dash until she is too tired, then Check.
Try it yourself
using UnityEngine;
using UnityEngine.InputSystem;
public class Dash : MonoBehaviour
{
public float distance = 3f;
public float cost = 40f;
void Update()
{
if (Keyboard.current.spaceKey.wasPressedThisFrame)
{
transform.position += Vector3.forward * distance;
}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular Turret10Project: Arena Survivor
The HeroEnemy Types