Custom methods for existing roblox classes

I would like to add a custom method to Soundgroup, an existing roblox class, that plays a random sound parented to it.

Is there a way to add a custom method to it that can be easily accessible by other scripts?

The code would go something like this:

function soundgroup.PlayRandom()
	local sounds = self:GetChildren()
	for i,v in sounds do
		if v.ClassName ~= "Sound" then 
			table.remove(sounds,i)
		end
	end
	sounds[math.random(1,#sounds)]:Play()
end

Is there a way to do this or am I going to have to find a more hacky way to accomplish this?

1 Like

Simple answer is you can’t. You cannot modify the Roblox API, everything is sandboxed for security reasons.

Long answer is you can emulate it using modules and type annotations, but it’s not going to be a smooth transition. Essentially you create your own class that you substitute for an actual API.

You can for example write a module that inherits the methods and functions of SoundGroup and parent it to game.

--define the type of the module to literally be SoundGroup, but add your own stuff
local module: typeof(SoundGroup) & {PlayRandom: () -> ()} = {}::any

--blah blah blah module code stuff

script.Parent = game --make it easier to use in other scripts
return module
--in your scripts, you require the module at the top to override the variable
local SoundGroup = require(game:WaitForChild('CustomSoundGroup'))

Note: the type annotation in the example might be illegal, I haven’t checked

3 Likes


Surprisingly not. (With strict mode on)

2 Likes