Why am I getting ' 17:29:44.236 - Workspace.Script:22: attempt to index nil with 'Parent''?

I’m trying to make a script where it chooses a random map, and it does that, but when I try and remove it I keep getting the error ’ 17:29:44.236 - Workspace.Script:22: attempt to index nil with ‘Parent’', I don’t know what I’m doing wrong though.

local RS = game.ReplicatedStorage
local Maps = RS.Maps
local CountDownTime = 5 --Time until a round starts
local RoundEndTime = 5 -- Time for a round
local TimeValue = script.TimeValue
local Mapstoload = Maps:GetChildren()

function roundIntermission()
	TimeValue.Value = CountDownTime
	for count = 1,CountDownTime do
		TimeValue.Value = TimeValue.Value - 1
		wait(1)
	end
end

function getRandomMap()
	local randomMap = Mapstoload[math.random(1, #Mapstoload)]
	randomMap.Parent = game.Workspace
end

function RemoveMap()
	randomMap.Parent = RS
end

function roundTime()
	TimeValue.Value = RoundEndTime
	for count2 = 1, RoundEndTime do
		TimeValue.Value = TimeValue.Value - 1
		wait(1)
	end
end

while wait() do
	roundIntermission()
	getRandomMap()
	roundTime()
	RemoveMap()
end

You cannot have a variable being made in a function and being reused in another. I would recommend calling the “randomMap” value outside of the function to make it globally and then inside the function you can give the variable a value. I hope this helped!

1 Like

randomMap is not defined, try to define it out of the function

2 Likes

I was thinking about doing that, but how would I make it randomly choose it again?

here is a fixed version of your script:

local RS = game.ReplicatedStorage
local Maps = RS.Maps
local CountDownTime = 5 --Time until a round starts
local RoundEndTime = 5 -- Time for a round
local TimeValue = script.TimeValue
local Mapstoload = Maps:GetChildren()
local randomMap

function roundIntermission()
	TimeValue.Value = CountDownTime
	for count = 1,CountDownTime do
		TimeValue.Value = TimeValue.Value - 1
		wait(1)
	end
end

function getRandomMap()
	randomMap = Mapstoload[math.random(1, #Mapstoload)]
	randomMap.Parent = game.Workspace
end

function RemoveMap()
	randomMap.Parent = RS
end

function roundTime()
	TimeValue.Value = RoundEndTime
	for count2 = 1, RoundEndTime do
		TimeValue.Value = TimeValue.Value - 1
		wait(1)
	end
end

while wait() do
	roundIntermission()
	getRandomMap()
	roundTime()
	RemoveMap()
end
1 Like