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

How to check events for multiple objects of the same name?

In my friends game, fish are spawned in a random location every 5 seconds. I have a script and I need it to check if any of the existing fish in workspace have been touched. How am I supposed to do this? I have tried writing:

	game.Workspace.Fish.Touched:Connect(function(hit) --Fires if fish touched
	if hit.Parent.Name == "WoodenFishingRod" then
		fish:Destroy()
		print("Fish Caught!")
		script.Value = script.Value + 1
	end
	
end)

but that only runs once, and it only checks for one fish. I need it to always be checking rather than only check once and also checking if anything called fish is touched. Does anybody know how to do this? Help is greatly appreciated. Thanks.

1 answer

✓ Accepted answer

You have a few options here. One would be creating a script in the fish and instead of indexing game.Workspace.Fish, you could instead index script.Parent and since all fishes would have the script, all fishes would have the event call. The issue with that though comes with the value you seem to be adding on line 5. I'm not sure where the script is parented, but I'm assuming every player or every fishing rod has one, so you would need to find out which fishing rod was hit.

Another alternative is simply iterating through wherever you keep all your fishes, which is apparently game.Workspace and applying the Touched event through there. That code would look like this:

for _, child in pairs(workspace:GetChildren()) do
	if child.Name == "Fish" then
		child.Touched:Connect(function(hit)
			if hit.Parent.Name == "WoodenFishingRod" then
				fish:Destroy()
				print("Fish Caught!")
				script.Value = script.Value + 1
			end
		end)
	end
end

2 comments

0

Added a 'while wait(5) do' to the 2nd script and it worked. Thanks!

0

Instead of adding a while wait(5) do, it's probably better to do a workspace.ChildAdded:Connect(function() ... end) because that will make the code run every time a new object is added in the workspace, rather than waiting every 5 seconds and checking that way.

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