I’m having the weirdest issue with my script. I’m trying to make a game where the player has to collect coins, but whenever I try to make a loop to detect when the player collides with a coin, the script just breaks down. Any help would be appreciated.
local coins = game.Workspace:GetChildren()
for _, coin in ipairs(coins) do
coin.Touched:Connect(function(player)
--this is where I'm having the issue
end)
end
The Touched listener takes in the part that it touched as a parameter, you can find the player by checking;
-- This is before the loop
local Players = game:GetService:("Players")
-- put this in the loop
if coin:IsA("BasePart") then
coin.Touched:Connect(function(hit)
if hit and hit.Parent:IsA("Model") and hit.Parent:FindFirstChild("Humanoid") and Players:GetPlayerFromCharacter(hit.Parent) then
local plr = Players:GetPlayerFromCharacter(hit.Parent)
end
end
end
I actually do want to get all of the objects in the workspace. I have a function that filters out the objects that are not coins, so the Touched event will only be connected to the objects that are coins. As for my mental illnesses, I prefer not to disclose that information
The problem with your code is that you do not have an identifier to differentiate between a coin and other parts in the workspace. I would suggest you to keep all the coins in a folder called “coins” and then write the loop. local coins = game.Workspace.coins:GetChildren()
for _,coin in pairs(coins) do
coin.Touched:Connect(function(player)
–This is where the player collects the coin
end)
end