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

NEEDS to be Local Script, and onTouch function doesn't work?

So recently I made a gem so when you collect it (touch it) it adds to the leaderboard. In order for this to work it NEEDS to be a local script, but for some reason I can't get a onTouch function to work with a local script.

function onTouched(hit)
	if hit == script.Parent then
		print("Stupid")
	
	end
	end

script.Parent.Touched:connect(onTouched)

1 answer

✓ Accepted answer

I see that you are using:

script.Parent.Touched:connect(onTouched)

which tells me that the local script is inside the gem itself.

Local scripts only run in certain places, i.e. the player and character, so they won't run if you place them inside the gem.

To fix this, I would put the script inside either the StarterPlayerScripts or StarterCharacterScripts, then replace script.Parent with a workspace-relative reference to the part. For example, if your part was called Part and inside a model called Gem which is directly parented to the workspace, then it would be:

function onTouched(hit)
	-- Code here.
end	

workspace.Gem.Part.Touched:connect(onTouched)

Additionally, hit will be the part that collided with the part that onTouched is connected to. In that case,

if hit == script.Parent then
	print("Stupid")
end

will never do anything, since the part can't collide with itself. If you want to check if the player was what collided with the part, you can use game.Players:GetPlayerFromCharacter(), like this:

if game.Players:GetPlayerFromCharacter(hit.Parent) == game.Players.LocalPlayer then

Hopefully this helps.

1 comment

0

Actually the Gem is inside the part, but I'll give this a try.

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