Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Cakes Made Mechanic Problems?

Asked by 8 years ago

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

Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

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)
Ad

Answer this question