Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why is this script not working, its to do with variables?

Why isn't the player variable bit working working, Whats wrong?

bin = script.Parent
function onTouched(part)
	local plr = part.Parent 
	-- my code

end

connection = bin.Touched:connect(onTouched)

2 answers

✓ Accepted answer

Hello.


The problem is that part.Parent is actually the character of a player, not the player.

So, you must use the GetPlayerFromCharacter() function. It will get the player from its character, part.Parent.


Also, note that anything can touch a part, not only players, so you have to have an if statement checking if the part touched was a player.


Recommendations:

  • Put "local" before declaring a function as it makes it local to its scope, similar to a local variable.

  • Put "local" before declaring a variable as it also makes it local to its scope.

  • You don't need a connection variable for the connection.

  • Use "connect" with an uppercase "C" as "connect" with a lowercase "C" is deprecated. It is never a good idea to use deprecated functions.


Fixed Script:

local bin = script.Parent

local function onTouched(part)
    local plr = game.Players:GetPlayerFromCharacter(part.Parent)
    
	if plr then
		-- Your Code Here
	end
end

bin.Touched:Connect(onTouched)

1 comment

0

Thx

I would use something like this

bin = script.Parent
function onTouched(part)
    local plr = part.Parent 
    -- my code

end

bin.Touched:connect(onTouched)

I removed the "connection =".

3 comments

0

Thx ill try it

0

Let me know if it works!

0

Let me know if it works!

This discussion is preserved as it was. New answers, comments, and votes are closed.