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

Cakes Made Mechanic Problems?

In my upcoming game Make a Cake Remastered, I'm working on a mechanic that keeps track of the # of cakes made by a player. It works by inserting a IntValue named the playername of that player (ex: An IntValue named "thebenster" inside the cake block), and then passes an invisible brick at the end of the factory, and awards the player in the "Cakes Made" leaderstat, and deletes the Value. The real kicker is if there are multiple IntValues in the cake from multiple players, I want it to award all of them in the "Cakes Made" leaderstat. As of now, this script is unstable, and if there are multiple values from multiple players, it may only award one player, or no one at all. Is there a better way to write this script?

function onTouched(part)

if part.Name == "FinishedCake" then
local a = part:GetChildren()
for i = 1, #a do
if (a[i].ClassName == "IntValue") then
	if game.Players:FindFirstChild(a[i].Name) == nil then return end		
	game.Players:FindFirstChild(a[i].Name).leaderstats:FindFirstChild("Cakes Made").Value = game.Players:FindFirstChild(a[i].Name).leaderstats:FindFirstChild("Cakes Made").Value +1
	a[i]:remove()
else return end
end
end
end
script.Parent.Touched:connect(onTouched)

1 answer

✓ Accepted answer

The method seems OK to accomplish this. Mostly your script just needs to be written with better style to be more readable.

I see one bug, which are the returns -- you ignore all of the values for one bad one. You instead want to continue only on good.

  • Use generic for with pairs instead of iterating from 1 to #a
  • Use good variable names
  • Save values into variables
  • Use :IsA
  • Tab your code correctly!
function onTouched(part)
	if part.Name == "FinishedCake" then
		for _, child in pairs(part:GetChildren()) do
			if child:IsA("IntValue") then
				local player = game.Players:FindFirstChild( child.Name )
				if player then
					local cakesMade = player.leaderstats:FindFirstChild("Cakes Made")
					if cakesMade then
						cakesMade.Value = cakesMade.Value + 1
						child:Destroy()
					end
				end
			end
		end
	end
end
script.Parent.Touched:connect(onTouched)

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