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

Script does not go into all parts?

So, I have multiple parts within on model, I want to make a script that says that if ANY of those parts gets hits, then do a given function. I figured the best was to reduce lag is to have one script that says if any of these parts in the model gets hit, then do so rather then having a script in every part.

If I were to put the script into every part it would appear like this [Works]:

function onTouch(hit)
local human = hit.Parent:findFirstChild("Humanoid")
	if (human ~= nil) then
		while (human ~= nil) do
		local s = wait(1)
		local health = human.Health
		if health > 0 and health < human.MaxHealth then
			local newHealthDelta = 0.01 * s * human.MaxHealth
			health = health + newHealthDelta
			human.Health = math.min(health,human.MaxHealth)
		end
		end
			if human.Health > human.MaxHealth then
		human.Health = human.MaxHealth
	end
	end
end

connection = script.Parent.Touched:connect(onTouch)

However, in my attempt to make it work by just putting one script in the model that access all parts, I think I am doing something wrong...

script.Parent:GetChildren()
function onTouch(hit)
local human = hit.Parent:findFirstChild("Humanoid")
	if (human ~= nil) then
		while (human ~= nil) do
		local s = wait(1)
		local health = human.Health
		if health > 0 and health < human.MaxHealth then
			local newHealthDelta = 0.01 * s * human.MaxHealth
			health = health + newHealthDelta
			human.Health = math.min(health,human.MaxHealth)
		end
		end
			if human.Health > human.MaxHealth then
		human.Health = human.MaxHealth
	end
	end
end

connection = script.Parent:GetChildren().Touched:connect(onTouch)

Can someone help me with what I am doing wrong please? I think I learned how to do this wrong seeing how I taught myself...

1 answer

You have to use GetChildren in a loop. Replace the last line:

for i, child in pairs (script.Parent:GetChildren()) do
	if child:IsA("BasePart") then -- consider only the Parts of the model
		connection = child.Touched:connect(onTouch)
	end
end

Also, I don't think you need to create a connection in there if you are not using it, so just put:

child.Touched:connect(onTouch)

2 comments

0

Ah I see. Thanks!

0

Yowelcome.

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