Can't get my script to work

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

that’s gets EVERYTHING in workspace , even things that aren’t coins…

And those things don’t have the .Touched event

1 Like

:GetChildren returns an array, not dictionary, you can use ipairs just fine.

I did not know that, I’ll delete my reply before I confuse anybody :sweat_smile:.

coin.Touched:Connect(function(player)

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
1 Like

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

Add a if statement that checks if the coins name is == ‘coin’

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

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.