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

Why does this script break after it has run several times?

This script works fine in my game. It controls a navigation GUI for bus routes. However, there an error that occurs during the game. The error is that Line 6 is referencing a nil value (even though when I test this via the Developer Console in game, the value is still there and not nil at all!) Then after thats happened the output goes silent and the script breaks. I have these scripts all over my game in bricks and they all break... Can anyone see why?

function onTouch(part)
	local player = game.Players:GetPlayerFromCharacter(part.Parent)
	if player then
		local human = part.Parent:findFirstChild("Humanoid") 
		if human then
			Value = game.Workspace:FindFirstChild(player.Name.."'s Car").StringValue.Value
			if Value == "TwentyTwo" then
				player.PlayerGui.GUI.Dashboard.Controls.Navigation.Direction.Image = "http://www.roblox.com/asset/?id=165473861"
			end
			wait(4)
			player.PlayerGui.GUI.Dashboard.Controls.Navigation.Direction.Image = "http://www.roblox.com/asset/?id=165477023"
		end
	end
end

script.Parent.Touched:connect(onTouch)

2 answers

✓ Accepted answer
value = game.Workspace:FindFirstChild(player.Name.."'s Car").StringValue.Value --In Lua, it's ussually considered a better style to have variables lower case. Your choice though. 

Your problem is that FindFirstChild() either returns the child you are looking for, or nil. If it returns the child you are looking for, then everything's fine and you set the variable to the StringValue's value. However, in the case that FindFirstChild() returns nil, you are attempting to do this:

value = nil.StringValue.Value

Which obviously results in an error.

To fix this, just use an if statement to check if it's nil or not..

if game.Workspace:FindFirstChild(player.Name.."'s Car") then
	value = game.Workspace[player.Name.."'s Car"].StringValue.Value
end

2 comments

0

Ahh yes! I was thinking this shouldn't happen because its activated by the driver, but failed to consider the passengers who dont have a bus (or Value) hence breaking the code. Thank you!

0

Sorry about that small typo I made. I guess it didn't matter though.

You have one word written wrong. onTouch is supposed to be spelled like this: OnTouch

1 comment

1

Its the name of my function so it doesn't matter how its spelt...

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