Is there something wrong with my script? Part change color onTouch

Hello! I was playing with random scripts because I got bored and confused on why this wasn’t working. I made it in two different ways and none of them worked, they all ended up turning red right when I clicked play. (I know this is a very simple script) It turns red automatically without me touching it.

local function yes()
	script.Parent.BrickColor = BrickColor.Red()
end

script.Parent.Touched:Connect(yes)```
----------------------------------------------
local Part = script.Parent

local function yes()
	Part.BrickColor = BrickColor.Red()
end

Part.Touched:Connect(yes)

What is this supposed to be? :thinking: Your full script should be this, and it should work just fine

local Part = script.Parent

local function yes()
	Part.BrickColor = BrickColor.new("Bright red")
end

Part.Touched:Connect(yes)
1 Like

Yea it’s not working, when I join the game, for some reason it’s already red. I haven’t even touched it yet and it turns red.

What’s happening is you aren’t filtering the Touched event, so when ANYTHING touches it it changes to red. Not when a player touches it.

1 Like

Make sure to set the Anchored property of the part to true, cause Touched relies on physics so it’d fire every time whenever a physics-based part touches it

The problem isn’t it being anchored or not. It’s just that the function they’re connecting doesn’t have a filter so anything that touches it (like I said above) registers the function and changes the color.

Ohhhh, thank you! Tiny mistakes. :cry:

It worked when I anchored it, I think it was the problem. :eyes:

That’s only if you want it to include only Players though

Of course if you’d want to get technical, you can use the GetPlayerFromCharacter() function to reference the Player that way & check if a Player did hit that part to change the BrickColor that way

local Part = script.Parent

local function yes(hit)
    local Player = game.Players:GetPlayerFromCharacter(hit.Parent)

    if Player then
	    Part.BrickColor = BrickColor.new("Bright red")
    end
end

Part.Touched:Connect(yes)

Setting the Anchored property to false would make this work too

1 Like

I know how it works, and that’s typically how people want it, or they want certain parts touching it to activate the function.

The only problem I have with the whole conversation is it seems, to me, like the OP thought that the whole problem with their script was that it needed to be Anchored to work properly. When Anchored/Unanchored was never the problem, just one of many solutions.

I understand that, but for the sake of the OP we should just keep it straight-forward & simple

He could just create another new topic detecting if a Player or a specific Part has hit the part or not, after all

1 Like