Skip to content

Lesson 8 of 9 · 24m

UI, Audio, and Save Data That Survive Contact

Implement readable interfaces, reliable audio playback, and versioned persistence without coupling every system to every other system.

Players rarely praise clean architecture, but they instantly feel the absence of it in UI, audio, and saving. Buttons do not scale, music doubles after restart, a crash deletes progress. These systems look peripheral and are actually trust infrastructure.

UI is state projection

UI should render state and send intent back into gameplay. It should not become the authoritative owner of gameplay state:

public class Hud : MonoBehaviour
{
    [SerializeField] private TMP_Text scoreText;
    [SerializeField] private Slider healthBar;

    public void Show(int score, float health01)
    {
        scoreText.text = score.ToString();
        healthBar.value = health01;
    }
}

A health system owns hit points. The HUD displays them. That separation lets you replace UI, test logic headlessly, and avoid bizarre bugs where damage depends on whether a menu was open.

Audio needs categories, not fifty loose sources

At minimum, separate music, sound effects, and UI sounds. Route them through mixer groups so volume settings control categories:

public void PlaySound(AudioClip clip, float volume = 1f)
{
    var source = pool.Get();
    source.outputAudioMixerGroup = sfxGroup;
    source.PlayOneShot(clip, volume);
}

If every script creates an AudioSource, restart behavior becomes a casino. Pool common one-shot sources. Keep looping sources under explicit ownership. Stop or fade audio during scene transitions intentionally.

Saving is a schema

Start with a serializable data object:

[Serializable]
public class SaveData
{
    public int version = 1;
    public int highestLevel;
    public int coins;
    public float musicVolume;
    public float sfxVolume;
}

Then write through one service. JSON plus Application.persistentDataPath is adequate for a small offline game:

var path = Path.Combine(Application.persistentDataPath, "save.json");
File.WriteAllText(path, JsonUtility.ToJson(data));

PlayerPrefs is acceptable for tiny options, but it becomes awkward for structured progression, migrations, and validation. Never treat either as secure against tampering; local saves are user-controlled input.

Field notes

  • JsonUtility does not serialize dictionaries and has limitations with polymorphism; know them before choosing it.
  • Write saves atomically when possible: write a temporary file, then replace the original. Power loss during write can corrupt the direct file.
  • Play audio through a real mixer early; retrofitting groups is tedious.
  • Test UI at the smallest supported viewport, not merely in the editor's generous Game view.

Was this lesson helpful?

Sign in to rate