Help with script

Hello,
I am trying to make that when the player touches a cube, it destroys it and increases the value of the cubes in leaderstats.

This code is in a Script:

local Cube = script.Parent

Cube.Touched:Connect(function(otherPart, player)
	if otherPart.Parent == player.Character then
		Cube:Destroy()
		player.leaderstats.Cubes.Value += 1
	end
end)

Possibly this code is very easy to solve, but I can’t find the solution, I’m a bit new to scripting.
Help would be appreciated

local Cube = script.Parent

Cube.Touched:Connect(function(touch)
    if touch.Parent:FindFirstChild("Humanoid") then
       game.Players:FindFirstChild(touch.Parent.Name).leaderstats.Cubes.Value += 1
       Cube:Destroy()
    end
end)
1 Like

thank you very much, it worked :smiley: !

local Players = game:GetService("Players")
local Cube = script.Parent

Cube.Touched:Connect(function(Hit)
	local HitModel = Hit:FindFirstAncestorOfClass("Model")
	if HitModel then
		local HitPlayer = Players:GetPlayerFromCharacter(HitModel)
		if HitPlayer then
			HitPlayer.leaderstats.Cubes.Value += 1
			Cube:Destroy()
		end
	end
end)

You should probably get the player instance as a reference from the player’s character as opposed to checking if a player’s name matches that of a character’s name.

@balotaxo use the one Forummer provided, it’s better as it checks if the thing that touched the Cube is really a player, mine just checks if it has a humanoid ( since npcs have humanoid too, and if a npc touches it it generates an error ).

1 Like