How to improve this piece of code?

local Items = game.ServerStorage.StorageFolder.ItemFolder
			local Wood = Items.Wood
			local Apple = Items.Apple
			local Number = math.random(1,6)
			bool = false
			script.Parent.Parent.Leaves.Anchored = false
			local goal = {
				Transparency = 1
			}
			local PartTween = TweenService:Create(script.Parent.Parent.Leaves, TweenInfo.new(2), goal)
			local PartTween2 = TweenService:Create(script.Parent.Parent.Trunk, TweenInfo.new(2), goal)
			PartTween:Play()
			PartTween2:Play()
			script.Parent.Parent.Leaves.CanCollide = false
			script.Parent.Parent.Trunk.CanCollide = false
			script.Parent.Parent.Part.CanCollide = false
if Number == 1 then
				local Wood1 = Wood:Clone()
				Wood1.Position = script.Parent.Parent.Trunk.Position
				Wood1.Parent = game.Workspace
			elseif Number == 2 then
				local Wood1 = Wood:Clone()
				local Wood2 = Wood:Clone()
				Wood1.Position = script.Parent.Parent.Trunk.Position
				Wood1.Parent = game.Workspace
				Wood2.Position = script.Parent.Parent.Trunk.Position
				Wood2.Parent = game.Workspace
			elseif Number == 3 then
				local Wood1 = Wood:Clone()
				local Wood2 = Wood:Clone()
				local Wood3 = Wood:Clone()
				Wood1.Position = script.Parent.Parent.Trunk.Position
				Wood1.Parent = game.Workspace
				Wood2.Position = script.Parent.Parent.Trunk.Position
				Wood2.Parent = game.Workspace
				Wood3.Position = script.Parent.Parent.Trunk.Position
				Wood3.Parent = game.Workspace
			elseif Number == 4 then
				local Apple = Apple:Clone()
				Apple.Position = script.Parent.Parent.Trunk.Position
				Apple.Parent = game.Workspace
			elseif Number == 5 then
				local Apple = Apple:Clone()
				local Wood1 = Wood:Clone()
				Apple.Position = script.Parent.Parent.Trunk.Position
				Apple.Parent = game.Workspace
				Wood1.Position = script.Parent.Parent.Trunk.Position
				Wood1.Parent = game.Workspace
			elseif Number == 6 then
				local Apple = Apple:Clone()
				local Wood1 = Wood:Clone()
				local Wood2 = Wood:Clone()
				Apple.Position = script.Parent.Parent.Trunk.Position
				Apple.Parent = game.Workspace
				Wood2.Position = script.Parent.Parent.Trunk.Position
				Wood2.Parent = game.Workspace
			end

Is there any way to improve this script as its pretty lengthy? This is really the only way I know how to make it randomized which is kind of embarrassing.

2 Likes

I want it also performant wise improved if it can be.

1 Like

Is this about random wood it will appear or clone?

2 Likes

basically it clones wood and apples depending on the numbervalue but the if statements are too long. Is there any easier way to this? (added full code) and it will appears

1 Like

Can we get a visual on how it runs currently if you don’t mind?

1 Like

its a tree system
it just drops woood or apples
random dropping system
but sure
roblox studio froze wait a sec

1 Like

robloxapp-20220111-0411491_Trim.wmv (1.0 MB)

the if statements drop random amount of wood depending on what the random number value is

1 Like

Ah alright, looks simple enough. I’ve kind of made a little chart so I can understand it a bit better. I’ll have your code done in a sec.

What I’m going to do in the improved version is create a randomization system with a rarity chart so you’ll have different values each results each time.

--[[
1 - Drops 1 piece of wood
2 - Drops 2 pieces of wood
3 - Drops 3 pieces of wood
4 - Drops 1 apple
5 - Drops 1 apple and 1 piece of wood
6 - Drops 1 apple and 2 pieces of wood
]

Seems to be functional just have to embed it alongside your code. I’ll be sure to explain whats happening throughout the code as well.

2 Likes

I got a offtopic question which is better to use game.serverstorage or game:GetService(“serverstorage”) are they different in preformance or anything really

2 Likes

I’m not to sure on that although it is recommended to use GetService over just directly using game.ServerStorage mostly due to if the name was changed you wont have an error getting stuff in it.

Now for the code, Test it out see if it works if not check the output for any errors creeping out of the script.

-- Variables
local Items = game.ServerStorage.StorageFolder.ItemFolder
local TweenService = game:GetService("TweenService")
local DebrisService = game:GetService("Debris") -- Adding a debug to destroy the wood if it isn't collected within a certain time period
local Wood = Items.Wood
local Apple = Items.Apple

-- Leaves Effect
local goal = {Transparency = 1}
local Leaves = script.Parent.Parent.Leaves
Leaves.Anchored = false
local PartTween = TweenService:Create(script.Parent.Parent.Leaves, TweenInfo.new(2), goal)
local PartTween2 = TweenService:Create(script.Parent.Parent.Trunk, TweenInfo.new(2), goal)
PartTween:Play()
PartTween2:Play()
script.Parent.Parent.Leaves.CanCollide = false
script.Parent.Parent.Trunk.CanCollide = false
script.Parent.Parent.Part.CanCollide = false
-- End

local RarityChart = { -- Holds rarity data for all the droppings for ex: Logs[1][1] has a 60% chance of dropping 1 log
	Logs = {
		{1, 60}, -- Arg1(Amount it will drop), Arg2(Rarity%)
		{2, 35}, -- Arg1(Amount it will drop), Arg2(Rarity%)
		{3, 10}, -- Arg1(Amount it will drop), Arg2(Rarity%)
	};

	Apples = {
		{1, 60}, -- Arg1(Amount it will drop), Arg2(Rarity%)
		{2, 35}, -- Arg1(Amount it will drop), Arg2(Rarity%)
		{3, 10}, -- Arg1(Amount it will drop), Arg2(Rarity%)
	};
}

function GetDropRate(Type) -- Function to return dropping amount for passed type
	if RarityChart[Type] then
		local types = {}
		local prng = Random.new()
		for a,b in ipairs(RarityChart[Type]) do
			local r = b[2]
			for t=1,r*100 do
				table.insert(types,b[1])
			end
		end

		return types[prng:NextInteger(1,#types)]
	end

	return 0
end

-- Drop Items
for Number = 1, GetDropRate("Apples") do -- Repeats function # of times the GetDropRate returned
	local DropApple = Apple:Clone()
	DropApple.Position = script.Parent.Parent.Trunk.Position
	DropApple.Parent = workspace
	
	DebrisService:AddItem(DropApple, 60) -- Will destroy apple if not collected within 60 seconds | If you don't want it to destroy just remove this line
end

for Number = 1, GetDropRate("Logs") do -- Repeats function # of times the GetDropRate returned
	local DropLog = Wood:Clone()
	DropLog.Position = script.Parent.Parent.Trunk.Position
	DropLog.Parent = workspace
	
	DebrisService:AddItem(DropLog, 60) -- Will destroy Log if not collected within 60 seconds | If you don't want it to destroy just remove this line
end
2 Likes

is this suppose to be in a local script?

Its setup to replace your old code, should be able to just copy and paste it over the old one.

2 Likes
local HitboxModule = require(game.ReplicatedStorage.HitboxModuleMain)
local TweenService = game:GetService("TweenService")
local Params = OverlapParams.new()
local Hitbox = HitboxModule:CreateWithPart(script.Parent, Params)
Hitbox:Start()
local health = math.random(35,45)
local bool = true
local Items = game.ServerStorage.StorageFolder.ItemFolder
local DebrisService = game:GetService("Debris") -- Adding a debug to destroy the wood if it isn't collected within a certain time period
local Wood = Items.Wood
local Apple = Items.Apple
local ongoing = false
local Trees = game.ServerStorage.StorageFolder.TerrainFolder.TreeFolder:GetChildren()
local respawn = math.random(30,40)
Hitbox.Touched:Connect(function(Object)
	if Object.Name == "Handle" and Object.Parent:FindFirstChild("IsAAxe") and ongoing == false then
		local status = Object.Parent:WaitForChild("Type")
		local HitSound = Object.Parent:WaitForChild("HitSound")
		if health > 0 then
			if status.Value == 'Wood' then
				health = health - 2
				HitSound:Play()
			elseif status.Value == 'Stone' then
				health = health - 4
				HitSound:Play()
			elseif status.Value == 'Iron' then
				health = health - 5.5
				HitSound:Play()
			elseif status.Value == 'Diamond' then
				health = health - 7
				HitSound:Play()
			end
			ongoing = true
			task.wait(1)
			ongoing = false
		elseif health <= 0 and bool == true then
			local goal = {Transparency = 1}
			local Leaves = script.Parent.Parent.Leaves
			Leaves.Anchored = false
			local PartTween = TweenService:Create(script.Parent.Parent.Leaves, TweenInfo.new(2), goal)
			local PartTween2 = TweenService:Create(script.Parent.Parent.Trunk, TweenInfo.new(2), goal)
			PartTween:Play()
			PartTween2:Play()
			script.Parent.Parent.Leaves.CanCollide = false
			script.Parent.Parent.Trunk.CanCollide = false
			script.Parent.Parent.Part.CanCollide = false
			-- End

			local RarityChart = { -- Holds rarity data for all the droppings for ex: Logs[1][1] has a 60% chance of dropping 1 log
				Logs = {
					{1, 60}, -- Arg1(Amount it will drop), Arg2(Rarity%)
					{2, 35}, -- Arg1(Amount it will drop), Arg2(Rarity%)
					{3, 10}, -- Arg1(Amount it will drop), Arg2(Rarity%)
				};

				Apples = {
					{1, 60}, -- Arg1(Amount it will drop), Arg2(Rarity%)
					{2, 35}, -- Arg1(Amount it will drop), Arg2(Rarity%)
					{3, 10}, -- Arg1(Amount it will drop), Arg2(Rarity%)
				};
			}

			function GetDropRate(Type) -- Function to return dropping amount for passed type
				if RarityChart[Type] then
					local types = {}
					local prng = Random.new()
					for a,b in ipairs(RarityChart[Type]) do
						local r = b[2]
						for t=1,r*100 do
							table.insert(types,b[1])
						end
					end

					return types[prng:NextInteger(1,#types)]
				end

				return 0
			end

			-- Drop Items
			for Number = 1, GetDropRate("Apples") do -- Repeats function # of times the GetDropRate returned
				local DropApple = Apple:Clone()
				DropApple.Position = script.Parent.Parent.Trunk.Position
				DropApple.Parent = workspace

				DebrisService:AddItem(DropApple, 60) -- Will destroy apple if not collected within 60 seconds | If you don't want it to destroy just remove this line
			end

			for Number = 1, GetDropRate("Logs") do -- Repeats function # of times the GetDropRate returned
				local DropLog = Wood:Clone()
				DropLog.Position = script.Parent.Parent.Trunk.Position
				DropLog.Parent = workspace

				DebrisService:AddItem(DropLog, 60) -- Will destroy Log if not collected within 60 seconds | If you don't want it to destroy just remove this line
			end
			task.wait(2)
			script.Parent.Parent.Trunk:Destroy()
			script.Parent.Parent.Leaves:Destroy()
			task.wait(respawn)
			local Chosen = Trees[math.random(1,#Trees)]:Clone()
			Chosen.PrimaryPart = Chosen.TreePosition
			Chosen:SetPrimaryPartCFrame(script.Parent.Parent.TreePosition.CFrame)
			script.Parent.Parent.TreePosition:Destroy()
			Chosen.Parent = game.Workspace.TerrainFolder.Trees
			script.Parent.Parent:Destroy()
		end
end
end)

like this? Cause if i replace all of it tree wont cut down theres also a red line under drop rate it says enclose line 15 i think says try changing it to local

1 Like

Try it out and see, I won’t know unless you test it out first.

2 Likes

Thank you very much! It worked!

2 Likes

Wait could I put 0 as a amount? or would it break?

1 Like

As a rarity? That is possible yes it.

The chances of it spawning nothing for one of them is 80%
The system is pretty simple to use once you use it a bit you’ll learn how to operate it a bit more if you read over it a few times.

local RarityChart = {
	Logs = {
		{0, 80},
		{1, 60},
		{2, 35},
		{3, 10},
	};

	Apples = {
		{0, 80},
		{1, 60},
		{2, 35}, 
		{3, 10},
	};
}
2 Likes

i was asking because I thought it would of cloned nothing and possibly break. Also thanks for the wood destroying if not collect part I really appreciate it

1 Like

Oh ok this is also the same I code I did when I’m gonna do random animation punch lol like this

local NumAnim = math.random(1, 3)--3 animation
if NumAnim == 1 then
punch1:Play()
elseif NumAnim == 2 then
punch2:Play()
elseif NumAnim == 3 then
punch3:Play()
end
--This code is just an example for my random punch animation

Welp thats it lol

1 Like

I suffered with elseif chains for quite a bit until I made the syntax completely variable, this way you only have to specify if then end once.

I know the post is solved, but I do want to share my take to whoever might find this useful.

Instead of this:

if Number == 1 then
   -- do something
elseif Number == 2 then
   -- do something
end

You could do something like this instead:

-- Get the Instances needed --
local Items = game.ServerStorage.StorageFolder.ItemFolder
local Wood = Items.Wood
local Apple = Items.Apple

-- Create a table or ModuleScript for what each number should do --
local Options = {
    [1] = {
        WoodQuantity = 2,
        AppleQuantity = 1
    },

    [2] = {
        WoodQuantity = 4,
        AppleQuantity = 2
    },

    -- etc.
}

-- Then calculate the position of the array that it should use. (Ex: Option 1 will give 2 wood, 1 apple if pulled.) --
local Math = math.random()

local RandomNumber = Math(1, #Options)
local Choice = Options[RandomNumber]

if Choice then
    -- Clone the amount of Wood specified in the Table --
    local NumberOfWood = Choice.WoodQuantity
    local NumberOfApples = Choice.AppleQuantity

    -- Clone Wood --
    for _ = NumberOfWood, 0, -1 do
        local NewWood = Wood:Clone()
        NewWood.Position = script.Parent.Parent.Trunk.Position
        NewWood.Parent = workspace
    end

    -- Then do the same for the apples --
    for _ = NumberOfWood, 0, -1 do
        local NewApple = Apple:Clone()
        NewApple.Position = script.Parent.Parent.Trunk.Position
        NewApple.Parent = workspace
    end
end

-- And now you're all done! Hope this helped.