Search code examples
eventsluagame-engineroblox

How to fire a remote event when a part is touched (Roblox Studio)


I'm trying to make it so when you touch a block in roblox studio it fires a remote event that tells A Gui that it can show up and tell the player they are touching the block. Here is the server script.

local ReplicatedStorage = game:GetService("ReplicatedStorage")

function partTouched(obj)

    if obj.Parent:findFirstChild("Humanoid") and obj.Parent.Name ~= "NextBot" then
        print(obj.Parent) -- prints my username
        local player = obj.Parent
        ReplicatedStorage.Insafety:FireClient(player)
        
    else
        print("Not alive... :(")
    end
 end


script.Parent.Touched:connect(partTouched) 

but every time it throws up the error FireClient: player argument must be a Player object - Server - Safezone:7 Thanks for any help!


Solution

  • The error is telling you that when you call Insafety:FireClient(player), the player object is not a Player.

    You are mistaking the player's Character model (the thing that runs around the game world) for the Player object itself (the object that represents the Roblox player that joined the game).

    Try using the Players:GetPlayerFromCharacter() function to easily get the Player from the character model in a Touched event :

    local Players = game:GetService("Players")
    local ReplicatedStorage = game:GetService("ReplicatedStorage")
    
    function partTouched(obj)
        -- escape if NextBot touches this
        if obj.Parent.Name == "NextBot" then
            return
        end
    
        -- Check if a player has touched the part
        local player = Players:GetPlayerFromCharacter(obj.Parent)
        if player then
            -- fire the event to the player that touched the part
            ReplicatedStorage.Insafety:FireClient(player)
        end
     end
    
    script.Parent.Touched:Connect(partTouched)