Scripting Book/Chapter 9
Introduction
This time we're going to learn how to make a script that when someone joins the game and says something, a message appears on the screen saying the player's name and what the player said.
Let's Begin
Events
The events we are going to use today are 'PlayerAdded' and 'Chatted'.
PlayerAdded
Fires a connected function when a player joins the server.
Chatted
Fires a connected function when a given player talks.
Player Entered function
First we need to make the player entered function. Remember it can be called whatever you want, but my function will be called 'onPlayerEntered' This function will contain 1 argument, mine is going to be called 'nP' short for newPlayer. Whenever we want to do something to the player who just joined the server, we index them with the argument, nP.
function onPlayerEntered(nP)
Chatted event connection
We need to connect the .Chatted event to the the onPlayerEntered function. This is known as an anonymous function.
function onPlayerEntered(nP) nP.Chatted:connect(function(msg) end
Adding the message
Now we need to instance the message, parent it in workspace. The code goes in the chatted function.
function onPlayerEntered(nP) nP.Chatted:connect(function(msg) m = Instance.new("Message", game.Workspace) end
Connecting the player's name to the text
We need to get the player's name and put it at the start of the message's text. To do this we put in m.Text =, then we need to add 'nP.Name', this would make a message displaying the text of the player who just talked's name.
function onPlayerEntered(nP) nP.Chatted:connect(function(msg) m = Instance.new("Message", game.Workspace) m.Text = nP.Name end
After that we need to put two dots in.
function onPlayerEntered(nP) nP.Chatted:connect(function(msg) m = Instance.new("Message", game.Workspace) m.Text = nP.Name.. end
Adding what the player said
Now we just need to add the string with a colon, so if SoulStealer9875 talked, a message appears on the script saying SoulStealer9875: .
function onPlayerEntered(nP) nP.Chatted:connect(function(msg) m = Instance.new("Message", game.Workspace) m.Text = nP.Name.. ": " end
Now we need two dots and the argument 'msg' that contains what the player just said.
function onPlayerEntered(nP) nP.Chatted:connect(function(msg) m = Instance.new("Message", game.Workspace) m.Text = nP.Name.. ": " ..msg end
Final touches
Finally we need to end the chatted function and include the remaining braket and we need a connection line for the onPlayerEntered function. After that we need to remove the message after three seconds.
Final script
function onPlayerEntered(nP) nP.Chatted:connect(function(msg) m = Instance.new("Message", game.Workspace) m.Text = nP.Name.. ": " ..msg wait(3) m:remove() end) end game.Players.PlayerAdded:connect(onPlayerEntered)