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

Why does this script not work?

Asked by 8 years ago

This script is trying to find out how long the player has been standing on a brick Output:


18:15:14.254 - Workspace.Part.Script:7: attempt to perform arithmetic on global 'howLong' (a nil value) 18:15:14.254 - Stack Begin 18:15:14.255 - Script 'Workspace.Part.Script', Line 7 18:15:14.255 - Stack End
while not script.Parent.Touched do
    howLong = 0 --This is how long the player has been on it
    print(howLong)
end

while script.Parent.Touched do
    howLong = howLong + 1
    if howLong == 20 then
        print("captured")
    wait(1)
end
end

0
Your script doesn't work? Dominus113 0 — 8y

1 answer

Log in to vote
0
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
8 years ago

Touched is not a Property of the Part object, it is an event. Events need to be setup with connection statements, tied to functions filled with code that you require to run whenever the event is fired.

Also, you should store the 'howLong' property in either the Player object or in separate values in a table since multiple people could be touching the part.

local touching = {}; --Who is touching?
local howLong = {}; --Time stats

--Track Touch Length
function track(player)
    --Every second
    while wait(1) do
        --If the player is still touching
        if touching[player] then
            --Then increment the stats
            howLong[player] = howLong[player] + 1 or 1;
            print(player..": "..howlong[player]);
        else
            --Otherwise, break the loop
            break
        end
    end
end

--Initiate Touch
script.Parent.Touched:connect(function(hit)
    --When something touches, check if it's a player
    local plr = game.Players:GetPlayerFromCharacter(hit.Parent);
    if plr then
        --If so, switch the bool
        touching[plr.Name] = true;
        --Track the touch Length
        track(plr.Name);
    end
end)

--End Touch
script.Parent.TouchEnded:connect(function(hit)
    --When something stops touching, check if it's a player
    local plr = game.Players:GetPlayerFromCharacter(hit.Parent);
    if plr then
        --If so, switch the bool
        touching[plr.Name] = false;
    end
end)
Ad

Answer this question