Click Detector Problem

Hey, Developers!

I’m trying to make it so that whenever you click the Button the part’s transparency, Reflectance and it’s color changes using Click Detector but the problem is that whenever I press the Button it says on the output that it is not a valid member of the Workspace .-.

Here’s the Picture of the Explorer:-
image

Here’s the Code:-

local prt = script.Parent

function OnClick(hit)
	local Hum = hit.Parent:findFirstChild("Humanoid")
	if Hum ~= nil then
		prt.Transparency = 0.5
		prt.Reflectance = 0
		prt.BrickColor = BrickColor.new("White")
	end
end

prt.ClickDetector.MouseClick:Connect(OnClick)

Here’s the Picture of the Output:-

ClickDetector.MouseClick passes the player who clicked the object.

I clicked it is not working, this is what I am trying to say ;-;

local prt = script.Parent

function OnClick()
   prt.Transparency = 0.5
   prt.Reflectance = 0
   prt.BrickColor = BrickColor.new("White")
end

prt:WaitForChild("ClickDetector").MouseClick:Connect(OnClick)
-- wait for it to load into the game

@HugeCoolboy2007 Uhh Can u explain the last line

`
Why did you use WaitForChild??

prt:WaitForChild(“ClickDetector”).MouseClick:Connect(OnClick)

Your script is inside of workspace, not the part.

When the server starts, objects have different points at which they load, server scripts loads into the game before certain objects. Therefore, you have to use WaitForChild. In other words, it pauses the script until the object exists so the script doesn’t throw any x is not a valid member of y 'z' errors.

No No No That was a free model script to check how ClickDetector Works.

Is your script supposed to be inside the part or workspace, in your message you’re saying that the ClickDetector should exist in workspace.

Lemme Edit the post to make things more clearer

I have edit the Post though :smiley:

If you made a mistake it’s okay, good to see that you got your solution.

1 Like

@HugeCoolboy2007 So basically, Roblox does not guarantee the time or order in which objects are replicated from the server to the client so we use WaitForChild for this purpose.

Correct, therefore, in situations where you feel the object might not have replicated yet, use WaitForChild.

1 Like

Um I just want confirm that the object can be anything right? i.e. Remote Events, ClickDetector, or a part

Yes, any object. However, some objects replicate before others as shown in the content streaming article:

So in some cases, WaitForChild, isn’t needed. But to be on the safe side, you can use it.

1 Like

Right Thanks for the help mate

1 Like