--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?
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).
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!)