I have a house in my game that when clicked while holding a hammer tool I have should get destroyed slowly by reducing its health, when health reaches 0 the house should get destroyed and the player should earn money.
However, every attempt I made to make a script for that failed.
Right now I am trying to do it like this:
In the group representing the house, I put a ClickDetector and a Script.
Here is the script
local house = script.Parent
local healthValue = Instance.new("IntValue")
healthValue.Name = "Health"
healthValue.Value = 100
healthValue.Parent = house
local function onHouseClicked(player)
print("House clicked:", house.Name)
-- Check if the player is holding a hammer
local character = player.Character
if not character then
print("Player character not found")
return
end
local tool = character:FindFirstChildWhichIsA("Tool")
if not tool then
print("Player is not holding a tool")
return
end
print("Tool used:", tool.Name)
-- Determine the damage based on the hammer used
local damageAmount = 0
local toolName = tool.Name
if toolName == "DefaultHammer" then
damageAmount = 10
elseif toolName == "Hammer2" then
damageAmount = 20
elseif toolName == "Hammer3" then
damageAmount = 30
end
print("Damage amount:", damageAmount)
-- Reduce the house's health
if healthValue.Value > 0 then
healthValue.Value = healthValue.Value - damageAmount
if healthValue.Value <= 0 then
-- House has been destroyed
print(house.Name .. " has been destroyed!")
house:Destroy()
else
print(house.Name .. " health reduced to " .. healthValue.Value)
end
end
end
-- Check if the house has a ClickDetector
local clickDetector = house:FindFirstChild("ClickDetector")
if clickDetector then
-- Connect the click event to the onHouseClicked function
clickDetector.MouseClick:Connect(onHouseClicked)
else
print("ClickDetector not found in house:", house.Name)
end
This script does nothing though and I can’t figure out why, if anyone has a better idea of how I can do this or how I can script this let me know.
By the way, this is the only game I ever tried making so be kind, its for my nephew