Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Touched function not working and doing what its supposed to do?

Asked by
CodeWon 181
3 years ago

When I touch the part, it does nothing and I don't know why.

Here is the script:

local MarketplaceService = game:GetService("MarketplaceService")
local gamepassId = 16463231

script.Parent.Touched:Connect(function(player)
    if MarketplaceService:UserOwnsGamePassAsync(player.UserId, gamepassId) then
        -- Double Coins
        player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 16
    else
        player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 8
    end

    player.Character.Humanoid.MaxHealth = 0 -- Respawn player after they collect their cash
end)

1 answer

Log in to vote
0
Answered by 3 years ago

Are you using a local script in the workspace? Local scripts don't run in the workspace and you need to use a normal script.

Also the .Touched event returns the part that got touched like the player's arm or leg so you need to get the parent of that part and see if you are able to get a player from the character first, so your code should something like this:

local Players = game:GetService("Players")
local MarketplaceService = game:GetService("MarketplaceService")
local gamepassId = 16463231

script.parent.Touched:Connect(function(hit)
    local player = Players:GetPlayerFromCharacter(hit.Parent) -- the parent of the touched part is expected to be a character
    if player == nil then
        print("Didn't touch a player")
        return
    end

    -- Your code here
        if MarketplaceService:UserOwnsGamePassAsync(player.UserId, gamepassId) then
            -- Double Coins
            player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 16
        else
            player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 8
        end

    player.Character.Humanoid.Health = 0 -- You should use Humanoid.Health not Humanoid.MaxHealth
end)
Ad

Answer this question