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

Trying to find the player that touched a block. Help?

Asked by 9 years ago

Here's what I tried

wait(1)
local character = game.Workspace.Player1 -- I need 'Player1' to be the player that touched the block.
local player = game.Players:GetPlayerFromCharacter(character)

if player then
script.Parent.Touched:connect(function(touchedEffect) 
    wait(0.1)
    script.Parent.Transparency = 1
    script.Parent.CanCollide = false
    script.Parent.Script.Disabled = true
    player.leaderstats.Pumpkins.Value = player.leaderstats.Pumpkins.Value +1
    print'Pumpkin 1 has been collected. It will return in ten seconds!'
    wait(10)
    print'Pumpkin 1 has returned. It is now collectable!'
    script.Parent.Transparency = 0
    script.Parent.CanCollide = true
    script.Parent.Script.Disabled = false
    end)
    end

1 answer

Log in to vote
2
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 years ago

You have no way of knowing if the Player you're looking for exists, or what their name is, before connecting the Touched event; you have to get their Player from inside the function.

You also did your debounce a little wrong.

local enabled = true
script.Parent.Touched:connect(function(touchedEffect)
    if not enabled then return end
    --[[The Touched event gives one argument to the connected function: the Part that fired the event. Your variable, touchedEffect, is not well-named in that regard, so I thought I'd let you know how that works.]]
    if not touchedEffect then return end --bullets for instance tend to be Removed() or Destroyed() after hitting things.
    local character = touchedEffect.Parent --[[Declaring the variables as 'local' while inside a block of code (this function in this instance) limits their "scope" to that block. That is, 'character' and 'player' (on the next line) are undefined outside of this function.]]
    local player = Game.Players:GetPlayerFromCharacter(character)
    if not player then return end --[[touchedEffect will always have a parent, but GetPlayerFromCharacter returns nil for non-character models]]
    script.Parent.Transparency = 1
    script.Parent.CanCollide = false
    player.leaderstats.Pumpkins.Value = player.leaderstats.Pumpkins.Value +1
    enabled = false
    print'Pumpkin 1 has been collected. It will return in ten seconds!'
    wait(10)
    print'Pumpkin 1 has returned. It is now collectable!'
    script.Parent.Transparency = 0
    script.Parent.CanCollide = true
    enabled = true
end)
1
Thanks! You're awesome :) SchonATL 15 — 9y
Ad

Answer this question