OnTouched Only work for players

I am trying to make a part where it uses an on touch script to run a function but I wanted to make the on touch only work to the player so if a Brick touches it does nothing to the brick only the player

I’ve tried writing this code but still does not work:

Burn = script.Parent

function onTouched(part)

part.BrickColor = BrickColor.new(26)

wait(.3)

part.Transparency = .2

wait(.1)

part.Transparency = .4

wait(.1)

part.Transparency = .6

wait(.1)

part.Transparency = .8

wait(.1)

part.Parent:Destroy()

end

connection = Burn.Touched:connect(onTouched)

Hello! :smiley:

Burn = script.Parent

function onTouched(part)

if part.Parent:FindFirstChild("Humanoid") then

part.BrickColor = BrickColor.new(26)

wait(.3)

part.Transparency = .2

wait(.1)

part.Transparency = .4

wait(.1)

part.Transparency = .6

wait(.1)

part.Transparency = .8

wait(.1)

part.Parent:Destroy()

end

end

connection = Burn.Touched:connect(onTouched)

This should work. How it works is it checks for an object only in a character.

3 Likes

Piggy-backing off what @Grayseon said, you can also use Players:GetPlayerFromCharacter() if you want ONLY players to change colour, and not any other NPCs that you have in your game and such

Ahhh! Thank you! This helped me because I have some NPCs In my game and don’t want the burn part to burn them!

1 Like

You can also use a for loop to change transparency instead of doing separate lines.

To break down the for loop, it works like this:

for Transparency = 0, .8, .2 do

A for loop takes 3 numbers, the starting number, the ending number, and the increment. Since you are increasing the transparency by .2 every .1 seconds, the increment should be .2.

Burn = script.Parent

function onTouched(part)
	if part.Parent:FindFirstChild("Humanoid") then
		part.BrickColor = BrickColor.new(26)
		wait(.3)
		
		for Transparency = 0, .8, .2 do
			part.Transparency = Transparency
			
			wait(.1)
		end
		
		part.Parent:Destroy()
	end
end

connection = Burn.Touched:connect(onTouched)
2 Likes

Oh! That works too! I had started scripting a few weeks ago that’s why I didn’t know!
Thank you!

1 Like

You’re welcome! If you have any further questions, just ask. The default increment for for loops is 1, forgot to mention that.

You can use game.Players:GetPlayerFromCharacter(hit.Parent) to check if character is player. This can be useful if you change the rig of player and humanoid name is for example "Slasher" you know what i mean?