Hello everyone im currently making a game and i need some items to spawn under trees. ive made the items spawn under the tree but the problem is if i have multiple trees the item will only spawn under the original tree.
ive tried finding a way to loop through all the trees that have the specific name of the fruit and make them spawn but i couldnt do that.
Can anyone help? Heres my code for the FruitsSpawningScript
local RS = game:GetService("ReplicatedStorage")
local OrangeTree = workspace:WaitForChild("OrangeTree"):WaitForChild("Fruits")
local OrangeClone1 = RS:WaitForChild("OrangeTreeFruits"):GetChildren()
local Players = game:GetService("Players")
local Lifetime = 80
local RandomAppleTimer = math.random(1, 2)
local function SpawnApple()
local function pickRandomApple(folder)
local randomIndex = math.random(1, #folder)
return folder[randomIndex]
end
local randomOrange = pickRandomApple(OrangeClone1)
local OrangeClone = randomOrange:Clone()
OrangeClone.Name = "Orange"
OrangeClone.Parent = OrangeTree
local Handle = OrangeClone:FindFirstChild("Handle")
if Handle then
Handle.Touched:Connect(function(otherPart)
local model = otherPart:FindFirstAncestorOfClass("Model")
if model then
local player = Players:GetPlayerFromCharacter(model)
if player then
Handle.Anchored = false
end
end
end)
end
local function setApplePos(apple)
local treePivot = OrangeTree.Parent:GetPivot() -- this is a cframe value
local spawnBox = workspace.OrangeTree:WaitForChild("SpawnBox1")
--[[
spawnbox is equal to a part in the workspace (or wheverer you want)
this part defines the specific spawning area minus the y because you will set the part
at the y-height you want to spawn the apples at
this code gets the size of said spawning part and changes the position of the apple before
it spawns to a random spot in the spawnPart size/2
--]]
local hitbox = spawnBox.Size
local ranSpawnX = math.random(-hitbox.X/2, hitbox.X/2)
local ranSpawnZ = math.random(-hitbox.Z/2, hitbox.Z/2)
apple.Handle.Position = Vector3.new(treePivot.X + ranSpawnX, spawnBox.Position.Y, treePivot.Z + ranSpawnZ)
end
setApplePos(OrangeClone)
coroutine.wrap(function() -- puts the delete timer in a new thread so the for loop can run without yielding
task.wait(Lifetime)
if OrangeClone.Parent == OrangeTree then -- checks if the apple has been picked up/doesnt exist in the tree anymore
OrangeClone:Destroy()
end
end)()
end
local spawn_Rate = 10 -- 10%
while true do
local luck = math.random(1,100)
if luck <= spawn_Rate then
SpawnApple()
end
task.wait(1)
end
here’s what i mean. Any feedback and help is appreciated,
thank you.
