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

Upon touching the cookie, why does it not give a point?

Asked by 3 years ago
Edited by JesseSong 3 years ago

Please encode Lua code in the Lua block code tag (look for the Lua icon in the editor).

As the title says, when I touch the cookie it does not give a point. If you're wondering what the purpose of the "HasCookie1" datastore, it is to prevent people from rejoining to pick up the cookie again & again awarding more points.

local DataStoreService = game:GetService("DataStoreService")
local HasCookie1 = DataStoreService:GetDataStore("HasCookie1")
amnt = 1 -- amount of cookie
function onTouched(part)
local h = part.Parent:findFirstChild("Humanoid")
if (h~=nil) then    
local thisplr = game.Players:findFirstChild(h.Parent.Name)      
local player = game.Players:GetPlayerFromCharacter(h.Parent)        
local playerKey = "id_" .. player.UserId        
if (thisplr~=nil) then          
local stats = thisplr:findFirstChild("leaderstats")         
if (stats~=nil) then                
local score = stats:findFirstChild("Cookies")               
if (score~=nil) and DataStoreService:HasCookie1(player.UserId, false) then                  
score.Value = score.Value + amnt                    
HasCookie1:SetAsync(playerKey, true)                
end         
end     
end     
script.Parent:remove()
end
end
script.Parent.Touched:Connect(onTouched) 
0
Please use a code block around code MightBeAHaxxer 24 — 3y
0
Why have you defined the player twice? is there a reason? MightBeAHaxxer 24 — 3y

1 answer

Log in to vote
0
Answered by 3 years ago

hello fellow scripter! I heard u needed help; i fixed it for you - and made it a lot more stable. your old code used a global function; which are not stable - i recommend using a local function more often. anyways - here's your fixed code!

local DataStoreService = game:GetService("DataStoreService")
local HasCookie1 = DataStoreService:GetDataStore("HasCookie1")

cookiesToGive = 1 -- amount of cookie

local function giveCookies(hit)
    local char = hit.Parent
    local humanoid = char:FindFirstChildWhichIsA("Humanoid")

    if humanoid then
        local player = game.Players:GetPlayerFromCharacter(char)

        if player then
            local hasCookie = HasCookie1:GetAsync("id_" .. player.UserId)
            if hasCookie == false then
                local leaderstats = player:WaitForChild("leaderstats")
                local cookies = leaderstats:FindFirstChild("Cookies")

                if cookies then
                    cookies.Value = cookies.Value + cookiesToGive
                    HasCookie1:SetAsync("id_" .. player.UserId, true)
                end
            else
                warn(player.Name .. " already has the cookie.")
            end
        end
    end
end

script.Parent.Touched:Connect(function(hit)
    giveCookies(hit)
end)

Ad

Answer this question