Help needed with Collection Service, again

Hello, dear community members,

I’m currently working on a game called “Cookie Simulator”. In-game, players must collect cookies by stepping on them. When a player touches a cookie, they receive a cookie via the leaderstats.

My question/problem is: What line should I add to define the part which has been touched by the player?

local function CookieTouched(Hit)
	local CheckHumanoid = Hit.Parent:FindFirstChild("Humanoid")
	if CheckHumanoid then
		local User = game.Players:GetPlayerFromCharacter(Hit.Parent)
		local Stats = User:findFirstChild("leaderstats")
		print(User.Name .. " touched a cookie!")
		if Stats then
			local CookiesStats = Stats:findFirstChild("Cookies")
			if MarketplaceService:UserOwnsGamePassAsync(User.UserId, GamepassId) then
				CookiesStats.Value = CookiesStats.Value + CookieToAdd * 2
				User.CustomSettings.LastCookieCollected.Value = CookieToAdd * 2
			else
				CookiesStats.Value = CookiesStats.Value + CookieToAdd * 1
				User.CustomSettings.LastCookieCollected.Value = CookieToAdd * 1
			end
			game.ReplicatedStorage.Events.CookieCollected:FireClient(User)
		end
	end
end

for _,CookiePart in pairs(CollectionService:GetTagged("SpawnCookies")) do
    CookiePart.Touched:Connect(CookieTouched)
end

Thanks for your help!

Your using the lua standard for functions, which is

local myFunction(foo)
     print(foo)
end
Event:Connect(myFunction)

For this, you may want to use the slightly more advanced technique of connecting functions, putting the code directly inside of the Touched listener.

for _,CookiePart in pairs(CollectionService:GetTagged("SpawnCookies")) do
     CookiePart.Touched:Connect(function(hit)
          local player = game.Players:GetPlayerFromCharacter(hit.Parent)
          if player then
              print(player.Name, "touched", CookiePart) -- this is the part that was touched
               -- your function
          end
     end)
end

This way, you will have access to the specific CookiePart that was touched without needing to pass that argument through another function.

1 Like

Thanks for your help, my script is now working!

1 Like