Issue with Defining Variables in a Local Script

Hi there,

I’m struggling to define a couple of variables (local script) at a set point in time of my round-based system. This is to enable a GUI to display when a puzzle of a map is interacted with (touched event). It seems that the KeycardInserter variable is the issue, by which as soon as the game loads, it attempts to index nil with ‘Puzzles’. At this point, I understand that the code is executing too fast and that there needs to be a way for it to run at a certain period in my game. A solution I have tried was to create a remote function that would execute when a map was called in my main script into my local one, but my current expertise is failing me.

Note that these variables must be generalised as I have multiple maps coming in and out of the workspace, and I have the same GUI needed to display.

local Map = game.Workspace.Map:FindFirstChildWhichIsA("Model")
KeycardInserter = Map.Puzzles.KeycardInserter.CardInserter.CardInserterPart

KeycardInserter.Touched:Connect(function(Hit)
	if Hit.Parent.Name == "Keycard" then
	-- etc., etc.

Many thanks :+1:

The Map variable is being set to whatever model is being found in workspace.Map, meaning that it’s probably getting the wrong thing and hence why it errors why you index it with Puzzle.

I forgot to add that my game operates by drawing a map out of ReplicatedStorage, and then places the map thereof into the workspace. So the question is how do you set this variable to “activate” when a model enters the workspace? Also bear in mind that this model is going into a folder within the workspace if that helps to clarify things!

You’d have to define it after the map is added into the folder, which you could detect using Instance.ChildAdded or Instance:WaitForChild()

The wiki pages should give you enough insight on how to use them, but if you’re confused, you could connect the ChildAdded event to a function that redefines the variable, like this:

local Map = nil -- we'll make it nil so any scripts know not to use the variable if it isn't defined yet
game.Workspace.Map.ChildAdded:Connect(function(child)
	if child:IsA("Model") then -- make sure that the instance being added is the correct one
		Map = child -- redefine the variable
	end
end)

I’m no expert programmer but this should make it so that defines Map every time a new one is placed in the folder. I’m not sure how the rest of your scripts work so you may need to make them all wait for this or just make sure they don’t run unless Map isn’t nil.

1 Like