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

Why does this script not work?

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

1 comment

0

Your script doesn't work?

1 answer

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)

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