luaroblox

How to get the name of a player that clicked a brick?


I have this script in a brick:

local giver = 1

function onClicked()
    game.Players.[I NEED THE PLAYER NAME HERE].leaderstats.Clicks.Value = game.Players.[I NEED THE PLAYER NAME HERE].leaderstats.Clicks.Value + giver
end

script.Parent.ClickDetector.MouseClick:connect(onClicked)

Now I need to somehow get the player's name that clicked it and put it where I need to.


Solution

  • The ClickDetectors's MouseClick event have the "Clicking Player" as parameter, so you can do it like this:

    local giver = 1
    
    function onClicked(Player)
        Player.leaderstats.Clicks.Value = Player.leaderstats.Clicks.Value + giver
    end
    
    script.Parent.ClickDetector.MouseClick:connect(onClicked)
    

    However, this requires the FilteringEnabled to be set to false (not recomended).

    To solve this, make a LocalScript in the brick with the code:

    script.Parent.ClickDetector.MouseClick:connect(function(Player)
        game.ReplicatedStorage:WaitForChild("BrickClick"):InvokeServer(script.Parent)
    end)
    

    And in a Script placed in the ServerScriptService put:

    local Listener = game.ReplicatedStorage:FindFirstChild("BrickClick")
    if Listener == nil then
        Listener = Instance.new("RemoteFunction")
        Listener.Name = "BrickClick"
        Listener.Parent = game.ReplicatedStorage
    end
    
    function Listener.OnServerInvoke(Player,Brick)
        Player.leaderstats.Clicks.Value = Player.leaderstats.Clicks.Value + 1
    end
    

    I won't point you to the wiki page for further reading, even thought it contains a bit of what you need, it contains too little information.

    The ClickDetector's MouseClick info, the guide about FilteringEnabled and the guide about RemoteFunctions are better.