Sometimes it returns nil how?

so my code

local function addTrees(chunk)
	local posGrid = chunk.positionGrid
	local instances = chunk.instances
	local chunkPosX = chunk.x
	local chunkPosZ = chunk.z

	for x = 0, X-1 do
		for z = 0, Z-1 do
			local pos = posGrid[x][z]

			if pos.Y >= -20 and pos.Y <=20 then

				math.randomseed(x * (chunkPosX+SEED) + z * (chunkPosZ+SEED))
				if math.random() < 0.1 then
					
					local tree
					if math.random(1,10) < 3.5 then
						tree = game.ReplicatedStorage:WaitForChild("TreeSmall"):Clone()
					end
					if math.random(1,10) < 1.5 then
						tree = game.ReplicatedStorage:WaitForChild("TreeBig"):Clone()
					end
					if math.random(1,10) < 5 then
						tree = game.ReplicatedStorage:WaitForChild("TreeMedium"):Clone()
					end
					
					print(tree) -- prints
					
					local cframe = CFrame.new(pos)
						* CFrame.new(
							math.random() * math.random(-10, 10),
							0,
							math.random() * math.random(-10, 10)
						)
						* CFrame.Angles(0, 2 * math.pi * math.random(), 0)
					
					tree:SetPrimaryPartCFrame(cframe) -- error occurs at
					tree.Parent = workspace.Tree

					table.insert(instances, tree)
				end

			end
		end
	end
end

returns nil for some reason (code from okeanskiy’s procedural gen)

i dont have any further explaination on this so pls gelp

There is no “return” line.

function doThing(boolValue)

   if boolValue then. -- if this is true, the function will return 1 as its value
      return 1
    end


   -- this is the same as “return nil”
end

print ( doThing(true) ) -- 1
print ( doThing(false) ) -- nil

Also, remember that you’re using Random to generate a tree. You must handle cases defensively where the tree value will be null. Otherwise your code will error.

   if tree ~= nil then
      -- do stuff to the tree
   end
2 Likes

i see thanks but after making this i solved it lol haha thanks

The 3 math.random(1,10) if check seems to be the problem.

Edit: Didn’t see that reply above

Great, no worries then.

Just remember then to mark your tickets as fixed or flag them for clean up.

Happy devving.

thanks you too and i will remember that

i dont think so but anyways ok

There is a small chance all the if check do nothing and tree will be nil