Hello, i am trying to make a miner job in my game. Im trying to make a stone thingy. You have to mine stone then wait for it to respawn. When i mine it, it respawns. But it just makes a backup of the stone in workspace for no reason. Here is the script:
hits = 0 script.Parent.ClickDetector.MouseClick:connect(function() hits = hits + 1 if hits == 3 then script.Parent = workspace -- just parent the script in a safe area because we need to remove it's parent game.Workspace.Mine.Stone:Destroy() -- remove the stone wait(3) local stone = game.ReplicatedStorage.Stone:Clone() -- clone the stone from replicatedstorage stone.Parent = game.Workspace.Mine -- set the parent to the mine script:Destroy() -- now safely remove the script because we dont need it end end)
Note: I added the comments to avoid some questions.
You are correct in thinking that the script you are using is a bit inefficient. Instead of copying the stone and script over and over again, it could just restore the originals! This script will do just that:
local hits = 0 local target = workspace.Mine.Stone local targetParent = target.Parent target.ClickDetector.MouseClick:connect(function(player) hits = hits + 1 if hits < 3 then return end --Hide stone target.Parent = nil --TODO Reward 'player' with inventory or money here wait(3) --Restore stone and allow mining again target.Parent = targetParent hits = 0 end)
Notes:
if hits < 3 then return end
is the same idea as if hits == 3 then
, but avoids an extra indentation.workspace:WaitForChild("Mine"):WaitForChild("Stone")
- this assumes that both Mine and Stone exist.Now, if you only have one rock in your entire place, this works fine. However, what if you want multiple rocks? Now, I don't know how you have your Mine
folder/model set up. Say that you have lots of Stone
s in there, but also other stuff that shouldn't be mined. Then we can go through each child and attach the event to any of them that are named "Stone". Each one can have its own local variable hits
so that they are kept separate.
local ch = workspace.Mine:GetChildren() --Get all the children in Mine for i = 1, #ch do --Go through each child if ch[i].Name == "Stone" then --If the child is what we're looking for: local target = ch[i] local hits = 0 target.ClickDetector.MouseClick:connect(function(player) hits = hits + 1 if hits < 3 then return end --Hide stone target.Parent = nil --TODO Reward 'player' with inventory or money here wait(3) --Restore stone and allow mining again target.Parent = targetParent hits = 0 end) end end
Since we declare hits
and target
inside the for loop, the function that is connected to the MouseClick event will receive those local variables. Each Stone will have its own function that will have its own target/hits variables.