I am trying to make a script that gets a random "Chunk" which is a group/model in a folder in server storage, The problem is that when it tries to pick a random "Chunk" it has this error code: Workspace.ObbyGenerator:9: attempt to index a nil value
Here is the script (It is a regular script in game.Workspace):
local ChunkSize = 144 local ChunkCounter = 0 local Chunks = {game.ServerStorage.Chunks:GetChildren()} math.randomseed(123) function CreateNewChunk() local ChunkCoordinate = ChunkSize * ChunkCounter local ChunkPicked = game.ServerStorage:FindFirstChild(Chunks[math.random(1, #Chunks)]):Clone() ChunkPicked.Parent = game.Workspace.Obby ChunkPicked:MoveTo(Vector3.new(ChunkCoordinate + 144, 0.5, 0)) ChunkCounter = ChunkCounter + 1 end local Obby = Instance.new("Model", game.Workspace) Obby.Name = "Obby" local firsthundredchunks = 100 repeat firsthundredchunks = firsthundredchunks - 1 ChunkCounter = ChunkCounter + 1 wait() until firsthundredchunks <= 0 while wait(3) do CreateNewChunk() ChunkCounter = ChunkCounter + 1 end
ooooh I get it now. What you are doing is requesting a table of children of an object by calling GetChildren()
aka:
children = obj:GetChildren() = { 1 = (all of obj's parent's).obj.Chunk, 2 = (all of obj's parent's).obj.Chunk, }
When you are using FindFirstChild
you just provide a string
a name and not an object (which you called by Chunks[math.random(1, #Chunks)])
So you can either FindFirstChild(chunk.Name)
(not recommended) or you can even better just do the first one as it's aka
local chunkPicked = Chunks[math.random(1, #Chunks)]:Clone()
And don't forget to account for lucyy's answer or else both will not work.
Remove the brackets on line 3
local Chunks = game.ServerStorage.Chunks:GetChildren()
What you're currently saying is get the children (which is a table), but you're storing the children in another table. Visually, this is what your problem looks like:
--Chunks table Chunks = { (another table containing all the game.ServerStorage.Chunks children) } print(Chunks[1]) -- prints the game.ServerStorage.Chunks:GetChildren() table which is inside the Chunks table