How to make a player triggered function?

Hey so i have been stuck at this for a little while now but i want it so when a player touches a brick it triggers a function eg when a player touches a brick is turns the brick into another colour?

-Thanks in advance.

You can use the Touched event for this, here’s some pseudocode:

script.Parent.Touched:Connect(function(hit) --//hit is the part that touched the object this script is in
local player = game.Players:GetPlayerFromCharacter(hit.Parent) --//See if a real player hit this part
if player then --//Test to see if 'player' exists
script.Parent.BrickColor = BrickColor.Random() --//Set the color of this object to a random color
end
end)

Reference: BasePart | Documentation - Roblox Creator Hub

3 Likes

Recommend watching tutorials/reading docs/browsing the devforum because from what I can see your new to scripting.

local part =  script.Parent -- Variable for Part
local debounce = false -- Cooldown so that the part only gets touched once per x amount of seconds
local cooldownTime = 1 -- How much time to wait for next touch


part.Touched:Connect(function(obj) -- When the Part is Touched, obj is the part that touched.
	
		if obj.Parent:FindFirstChild('Humanoid') then -- Assuming the part that touched the part is a player limb, so the humanoid would be stored in the character.
		local human = obj.Parent.Humanoid -- Variable for Humanoid
		if human.Health > 0 then -- If player is alive		

		if debounce == false then -- If debounce is turned off (won't work if debounce is on)
			debounce = true -- Turn debounce on	

			part.BrickColor = BrickColor.Random() -- Make part brick color to a random brick color.
	
		wait(cooldownTime) -- Wait the cooldown time
		debounce = false -- Turn debounce off	
		
			
			end
		end
	end	
end)

If this worked, please click the “Solution” on my comment. Thank you! :slightly_smiling_face:

5 Likes