Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to disable all scripts that are a descendant of a model?

So I have this hierarchy for instance:

ModelA
 ScriptA
 ScriptB
 ModelB
  ScriptC
  ScriptD
 PartA
  ScriptE
ScriptF

How would I disable every script inside ModelA (A,B,C,D,E) but not the one outside it (F)? To be clear I don't want to have to individually target all of them, I want something like:

ModelA:Find("Script").Enabled = false

Is there any way to accomplish this?

2 answers

✓ Accepted answer

If you know that all of the scripts are precisely the children of children, you could just write a nested loop:

for _, child in pairs(model:GetChildren()) do
	for _, grandchild in pairs(child:GetChildren()) do
		if grandchild:IsA("Script") then
			grandchild.Disabled = true
		end
	end
end

Of course, if you don't know that (and probably you don't / shouldn't confine yourself to that) then you should turn to recursion.

A descendant of a model is either a child or a descendant of a child. With that recursive definition we can define something to make a list of all descendants:

function descendants( model )
	local allDescendants = {}
	for _, child in pairs(model:GetChildren()) do
		table.insert(allDescendants, child) -- Children are descendants
		for _, childdesc in pairs( descendants(child) ) do
			table.insert(allDescendants, childdesc)
			-- Descendants of children are descendants of model
		end
	end
	return allDescendants
end

for _, descendant in pairs(descedannts(model)) do
	if descendant:IsA("Script") then
		descendant.Disabled = true
	end
end

Or, just wrap the modification into the recursive function and avoid adding to tables (though this makes the descendants function not reusable):

function disableScripts( model )
	if model:IsA("Script") then
		model.Disabled = true
	end
	for _, child in pairs(model:GetChildren()) do
		disableScripts(child)
	end
end

Use a loop to iterate over each item and if the value is == to the script, then set it to false.

1 comment

0

Are you sure there isn't a way similar to the example I gave? If not, how do I iterate over all children as well as the original

This discussion is preserved as it was. New answers, comments, and votes are closed.