Touched event for UI not firing

Hey there, I am currently trying to make it so that when I touch a part in workspace, a textLabel’s text changes. But it doesn’t seem to work. Can anybody help me figure out what’s wrong with my script?

Script:

local x = "fire"
local TextLabel = script.Parent
local labelChanger = game.Workspace.LabelChanger

local function onTouched(bodyPart)

local character = bodyPart.Parent:FindFirstChild("Character")

if bodyPart.Parent == character then
		TextLabel.Text = x
		print("logged")
	end
end

labelChanger.Touched:Connect(onTouched)

image

Firstly, change your Script to a LocalScript. Use this code instead.

local x="fire"
local TextLabel=script.Parent
local Part=game.Workspace.LabelChanger
Part.Touched:Connect(function(Hit)
	if Hit.Parent==game.Players.LocalPlayer.Character then
		TextLabel.Text=x
	end
end)

But how? Why doesn’t my script work? It is because it wasn’t a local script, does it matter though?

Localscripts are ideal for managing client sided tasks.
Scripting user-interface (screengui) for individual clients respectively is hence done by making use of LocalScripts.

By making use of a script, and not a localscript, you will not be able to fire remote events and achieve a client-server communication. Moreover you will not be able to get a reference to the LocalPlayer by making use of game.Players.LocalPlayer.

This in many scenarios will cause issues in the long run, and hence LocalScripts are preferred for interfaces.

Your script does not work because of this line. The correct code should be

local character = bodyPart.Parent

adding onto this, you need to check whether the character is indeed our own character and not that of someone else in the server.

-- your wrong code
if bodyPart.Parent == character then
		TextLabel.Text = x
		print("logged")
	end
end

the correct code should be

-- ideal code
if character==game.Players.LocalPlayer.Character then
		TextLabel.Text = x
		print("logged")
	end
end
--[[
we are ensuring that the character which touched the part is us, and not any other
Player in the server
--]]

But I am searching for the character, I have seen ALL of kill brick scripts use this. They first find the character, and then from that character, they take the humanoid and set it’s health to 0.

Moreover, why I can’t I use :FindFirstChild?

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.