Function keeps indexing "nil" instead of picking from a table

I’m having a small issue with my code here. I’m trying to get this system to work where it picks a random monster and then have it spawn in one of my spawn points. It’s hiccupping here:

function chooseMonster()
	return pickedMonster[math.random(#pickedMonster, 1)]
end

For whatever reason, it’s just not picking one. For context, here’s the whole script. It’s contained in a module script:

local gameManager = {}
local pickedMonster = {}
local monsterTypes = game:GetService('ServerStorage').monTypes:GetChildren()

function gameManager:spawnMonsters()
	print(monsterTypes)
	local spawnLocations = workspace.SpawnPoints:GetChildren()
	for i=1, #spawnLocations, 1 do
		local position = spawnLocations[i].Position
		local monster = chooseMonster():Clone()
		monster.Parent = game.Workspace
		monster:MoveTo(position)
	end
end

for i=1, #monsterTypes, 1 do
	local item = game:GetService('ServerStorage').monTypes:FindFirstChild(monsterTypes[i])
	table.insert(pickedMonster, item)
	print(monsterTypes[i], pickedMonster[i])
end


function chooseMonster()
	return pickedMonster[math.random(#pickedMonster, 1)]
end

return gameManager

I think its because this kinda code just doesn’t work in a module script? I’m not too sure. Would anyone be able to tell me whats up? Thanks in advance.

math.random(a, b) must always have a < b. #pickedMonster is likely a higher number than 1. You just need to switch their order.

1 Like

Doing that fires this error:

Seems like the issue lies elsewhere.

Edit: wrote the wrong word. fixed now.

That error means that a is less than b. So, that’s weird.

I’ll get back to you when I can as I am struggling with a problem as well (speaking of which I’m about to post on it). But from a quick glance, it looks like you’re running the spawnMonsters function before the for loop even starts.

The problem could be this. Does this loop print out anything?

for i=1, #monsterTypes, 1 do
	local item = game:GetService('ServerStorage').monTypes:FindFirstChild(monsterTypes[i])
	table.insert(pickedMonster, item)
	print(monsterTypes[i], pickedMonster[i])
end

Sorry about the late reply, its pretty early in the morning where I am so i dozed off. Apologies.

image

Here’s what that print code attached to the loop puts out. Gonna take a guess and that means that I’m missing something that the table needs to insert.

Edit: fixed redundancy.

Why even bother with the loop creating the pickedMonster table, you already have a table of monsters in monsterTypes.

function chooseMonster()
	return monsterTypes[math.random(1, #monsterTypes)]
end

This fixed it. Thank you very much! I’m thinking I over-thunk the problem. LOL

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.