Cannot use function parameters

--local script in StarterPlayerScripts

local CollectionService = game:GetService("CollectionService")
local connections = {}

local function OnClick(player, object)
-- I want this function to run when the local player clicks any object tagged with Clickable
	print(object.Name)
end

local function onInstanceAdded(object)
	local clickDetector = Instance.new("ClickDetector")
	clickDetector.Parent = object
	connections[object] = object.ClickDetector.MouseClick:Connect(OnClick(object))
end

for _, object in pairs(CollectionService:GetTagged("Clickable")) do
	onInstanceAdded(object)
end

On start, code prints the object name without the player clicking then gives this error
"Attempt to connect failed: Passed value is not a function"
When I call OnClick without the object parameter It seems to be good.
How can I pass the object correctly?

How are you calling the function OnClick? Also which line does this error occur on?

I call it in this line, erorr just says - Studio

1 Like
	connections[object] = object.ClickDetector.MouseClick:Connect(OnClick(object))

instead of doing that, you would have to do this:

	connections[object] = object.ClickDetector.MouseClick:Connect(function()
    OnClick(object)
end)
1 Like

Is this line in the same script as the local script above?

yes it is in the same script above

1 Like

is it above or below where you define the function OnClick? If it’s above the line where you define the function OnClick, then change OnClick to just a function instead of a local function (ie. remove the local part).

Also try what @PoppyandNeivaarecute said

It would be how they are connecting it, so it is the :Connect() line.

:Connect() requires a function to be passed. In the provided code, Merakkli passes OnClick(object). While it may look like you are passing a function, you are actually passing the returned value of the OnClick function, which will be nil as no value is returned. As far as I know, the only way to pass a parameter to a function while having it be connected to an event, is to call / create a function that seperately calls the main function with the parameters, as I did in the code I provided earlier.

(I’m terrible at writing and explaining, so if you want more information / clarification, let me know!)

2 Likes

Ohhhhhhh I see, I was wondering why you’d need to add function() lol. Thanks for the help and clarification, it was well explained :pray:

p.s how do you make those buttons things :eyes:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.