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

How do I get the LocalPlayer in a TextLabel?

In my game, I am trying to make a private messaging system. I know that Roblox has its own, but this can have groups of people and some other cool stuff. Anyways, I'm trying to make the chat parts and the label can't get the LocalPlayer or the text in the text box, even though it is working with the print command perfectly. Heres my code.

script.Parent.MouseButton1Click:Connect(function(player)
	print(game.Players.LocalPlayer,': ',script.Parent.Parent.message.Text)
	script.Parent.Parent.messages.msg1.Text = game.Players.LocalPlayer,': ',script.Parent.Parent.message.Text
	script.Parent.Parent.message.Text = ''
end)

EDIT: Sorry if the question sounded weird or something, I'm new to coding and this website even. Thanks for understanding.

1 answer

✓ Accepted answer

The problem is that Roblox stores things inside Player objects (TextLabel in this case) locally. This basically means that each player sees different things, in most cases this feature is pretty useful but other times it might be a big roadblock.

The solution might seem a bit complicated but it's actually really simple, You can use RemoteEvents to communicate between local and global objects.

Inside "Communication control" script (server-side):

local remote1 = Instance.new("RemoteEvent")
remote1.Parent = game.ReplicatedStorage
remote1.Name = "receiveMessage"
local remote2 = Instance.new("RemoteEvent")
remote2.Parent = game.ReplicatedStorage
remote2.Name = "sendMessage"

remote1.OnServerEvent:Connect(function(c,message,sender,receivers)
	for i, v in pairs(receivers) do
		remote2:FireClient(v, message, sender)
	end
end)

Inside "message reader" localscript (client-side):

local remote2 = game.ReplicatedStorage.sendMessage
local text = script.Parent.TextLabel

remote2.OnClientEvent:Connect(function(message, sender)
	text.Text = sender.name..": "..message
end)

Inside "message sender" localscript (client-side):

local message = "Hello world!"
local sender = game.Players.LocalPlayer
local group = {game.Players.LocalPlayer} -- list of players that should receive the message
local remote1 = game.ReplicatedStorage.receiveMessage

script.Parent.MouseButton1Click:Connect(function()
	remote1:FireServer(message,sender,group)
end)

Once again, this might seem a bit complicated. You might have to figure some things out on your own.

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