Add Gameplay Music

Adding music to the game can improve the experience for the player. In this case, when the nav mesh has been generated, some music will then start to play while the game is being played.

Create Audio Folder

In the Hierarchy create a Client Context folder called Audio.

Add Music

From Core Content find some music that would suit your game and add it to the Audio folder in the Hierarchy. In this case, the “Furious Epic Battle” Music Construction Kit (Sections) 01 will be used.

Make sure your audio does not have Auto Start enabled. The audio will be played from the PlayerClient script. Also disable Spatialization, Attenuation, and Occlusion.

Update PlayerClient Script

The PlayerClient script will need a reference to the music you added so it can play it when the UI has been turned off.

Add your music to the PlayerClient script as a custom property. Rename the property to Music.

Add Variable

Add the variable to the script so you have a reference to the music property.

local MUSIC = script:GetCustomProperty("Music"):WaitForObject()Code language: Lua (lua)

Update HideUI Function

When the HideUI function is called, that means the player is ready to play the game, so the music can also start playing by calling Play.

local function HideUI()
	MUSIC:Play()
	UI_CONTAINER.visibility = Visibility.FORCE_OFF
endCode language: Lua (lua)

The PlayerClient Script

local UI_CONTAINER = script:GetCustomProperty("UIContainer"):WaitForObject()
local GENERATED_MAP = script:GetCustomProperty("GeneratedMap"):WaitForObject()
local PROGRESS = script:GetCustomProperty("Progress"):WaitForObject()
local MUSIC = script:GetCustomProperty("Music"):WaitForObject()

local function HideUI()
	MUSIC:Play()
	UI_CONTAINER.visibility = Visibility.FORCE_OFF
end

local function UpdateProgress(obj, prop)
	if prop == "grid" then
		local val = GENERATED_MAP:GetCustomProperty("grid")

		if val > 0 then
			PROGRESS.text = string.format("%.2f%%", (GENERATED_MAP:GetCustomProperty("grid") / 2) * 100)
		end
	elseif prop == "mesh" then
		local val = GENERATED_MAP:GetCustomProperty("mesh")

		if val > 0 then
			PROGRESS.text = string.format("%.2f%%", 50 + (val / 2) * 100)
		end
	end
end

GENERATED_MAP.customPropertyChangedEvent:Connect(UpdateProgress)

UpdateProgress(GENERATED_MAP, "grid")
UpdateProgress(GENERATED_MAP, "mesh")

Events.Connect("HideUI", HideUI)Code language: Lua (lua)

Test the Game

Test the game to make sure the music starts playing when the UI is turned off.

Scroll to Top