This commit is contained in:
Joe 2026-02-02 12:08:47 -06:00
parent a9b4f8e83b
commit e6efc04756
8494 changed files with 495610 additions and 0 deletions

View file

@ -0,0 +1,447 @@
---
title: Else/if practice with giving points
description: Create a part that gives players points using if and else statements in Luau.
next: /tutorials/fundamentals/coding-4/landing
prev: /tutorials/fundamentals/coding-3/multiple-conditions
---
This project will use conditional statements to create a part that will give or subtract points on a leaderboard depending on what color the part is when touched. If blue, then it'll give players a few points. If green, then it'll give a lot of points. Finally, if red, then it'll take away points.
<video controls src="../../../assets/education/coding-3/coding3_colorPointBlockFinalizedExample.mp4" width="100%"></video>
## Set up the project
The point giving part can be added into any project where points are relevant. For instance, an adventure game where players collect points.
### Point tracking
To setup this project, you'll need a leaderboard to track the points and a part that changes colors. Code for the leaderboard will be provided.
1. Create a new script in **ServerScriptService** named Leaderboard. Copy and paste the code below into the script.
```lua
--In ServerScriptService, create a script named PlayerSetup with the contents below.
local Players = game:GetService("Players")
local function onPlayerJoin(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
-- Example of an IntValue
local points = Instance.new("IntValue")
points.Name = "Points"
points.Value = 0
points.Parent = leaderstats
end
-- Run onPlayerJoin when the PlayerAdded event fires
Players.PlayerAdded:Connect(onPlayerJoin)
```
### Color changing part
The script will cycle through three different colors for the part. Each color will have a variable to store it's RGB value, a data type that includes a set of three numbers (red, green, blue) that create colors.
1. Create a part named PointPart with an attached script named PointScript.
2. In PointScript, use `script.Parent` to refer to the part.
```lua
local pointPart = script.Parent
```
3. Create variables to store the different colors. Each variable should be set to `Datatype.Color3.fromRGB()`, which creates a color value.
- **Blue** (Some Points): (0, 0, 255)
- **Green** (Many Points): (0, 255, 0)
- **Red** (Lose Points): (255, 0, 0)
```lua
local pointPart = script.Parent
-- Colors
local blue = Color3.fromRGB(0, 0, 255)
local green = Color3.fromRGB(0, 255, 0)
local red = Color3.fromRGB(255, 0, 0)
```
4. Add variables for a small amount of points, a larger amount of points, and a third for removing points.
```lua
-- Colors
local blue = Color3.fromRGB(0, 0, 255)
local green = Color3.fromRGB(0, 255, 0)
local red = Color3.fromRGB(255, 0, 0)
-- Points values
local smallPoints = 10
local largePoints = 50
local losePoints = 100
```
### Add the players service
To award points, you'll need to get access to the player's information which is stored in the Explorer under Players, and is separate from the character object. This is where information like leaderboard stats can be found.
You can do so by adding the **Players** service to your script. **Services** are additional sets of pre-built functions made by Roblox engineers to save you time.
1. Get the **Players** service by typing:
`local Players = game:GetService("Players")`
```lua
-- Points values
local smallPoints = 10
local largePoints = 50
local losePoints = 100
-- Services needed
local Players = game:GetService("Players")
```
### Functions and events
PointsScript will need two functions. The first function will give and subtract parts. The second function will check if a player has touched the part. These functions will then be connected with a touch event, which runs whenever that part is touched.
1. Create a new function named `givePoints()` and a parameter named `player`. Inside, add a print statement to use for testing.
```lua
local Players = game:GetService("Players")
-- Gives or subtracts points
local function givePoints(player)
print("Giving player points")
end
```
2. Under that, create a second function named `partTouched()` with a parameter named `otherPart`.
```lua
-- Gives or subtracts points
local function givePoints(player)
print("Giving player points")
end
-- Checks if player touched the part
local function partTouched(otherPart)
end
```
3. Inside the function, use the function `GetPlayerFromCharacter()` to check if there's a player in the otherPart variable.
```lua
-- Checks if player touched the part
local function partTouched(otherPart)
local player = Players:GetPlayerFromCharacter(otherPart.Parent)
end
```
4. If a player touched the part, it'll be stored inside the player variable. If not, the variable will stay empty. On your own:
- Inside the function, check if player has a value. If there is, then call `givePoints(player)`.
- Beneath the function, connect `partTouched()` to the Touched event of `pointPart`.
```lua
-- Checks if player touched the part
local function partTouched(otherPart)
-- Gets the player if one touched the part
local player = Players:GetPlayerFromCharacter(otherPart.Parent)
if player then
givePoints(player)
end
end
pointPart.Touched:Connect(partTouched)
```
5. **Run** the project. Whenever a player touches the part, you should see a message in the Output window saying: `"Giving player points"`
**Troubleshooting Tips:**
- Check that `"Players"` in `game:GetService("Players")` is capitalized and in quotations.
- `partTouched()` should be connected to pointPart's `Touched` event.
## Create Looping Colors
To loop through colors, the script will use a while =loop that changes the part's color every few seconds. The condition for this loop will be true, so it can run indefinitely.
1. At the end of the script, create a new while loop where the condition is true, meaning the loop always runs.
```lua
-- Checks if player touched the part
local function partTouched(otherPart)
-- Gets the player if one touched the part
local player = Players:GetPlayerFromCharacter(otherPart.Parent)
if player then
givePoints(player)
end
end
pointPart.Touched:Connect(partTouched)
-- Loops through colors
while true do
end
```
<Alert severity="info">
If the while true do loop is not at the bottom of the script, any code below it will never be run. Since the while loop doesn't stop, it'll keep running the loop instead of any code below it.
</Alert>
2. On your own, code a while true do loop that changes pointPart to the color variables you've created. Don't forget to use `Library.task.wait()` between colors. When finished, check your code against the version below.
```lua
-- Loops through 3 colors, waiting between each color
while true do
pointPart.Color = blue
task.wait(3)
pointPart.Color = green
task.wait(2)
pointPart.Color = red
task.wait(1)
end
```
3. Play-test and check that all three colors loop without stopping.
<img src="../../../assets/education/coding-3/colorPoint_loopingColors.gif" width="50%" />
### Troubleshooting tips
At this point, if the color looping doesn't work as intended, try one of the following below.
- Check that the while loop is at the **bottom** of the script, below the Touched event. If the loop is not at the bottom, it'll keep other parts of the script from running correctly.
- Check that each color inside `Datatype.Color3.fromRGB()` is correctly written. There must be three numbers between 0 and 255 separated by commas, like `(255, 50, 0)`.
## Give players points
Players will be given points based on the current color of the part when they touch it.
### Find the current color
Whenever a player touches the part, the script will need to know the current color of the part to award points later.
1. Find `givePoints()`. Replace your testing message with a variable for the current color of pointPart. This variable will determine how many points the player gets (or loses).
```lua
local function givePoints(player)
local currentColor = pointPart.Color
end
```
2. To affect a player's points, that function needs access to the player's leaderboard. Create a variable to store it.
```lua
local function givePoints(player)
local currentColor = pointPart.Color
local playerStats = player:WaitForChild("leaderstats")
end
```
3. Now add a variable to get the player's Points value, which is a child of their leaderboard.
```lua
local function givePoints(player)
local currentColor = pointPart.Color
local playerStats = player:WaitForChild("leaderstats")
local playerPoints = playerStats:WaitForChild("Points")
end
```
### Give or subtract points
Next, you'll use if and elseif to give or subtract points depending on the color of the part when touched. Remember that blue provides a small amount, green provides many, and red subtracts points.
1. Inside `givePoints()`, beneath the variables, use an if statement to check if the current color is blue and if so then add `smallPoints` to the player's current points value.
```lua
local function givePoints(player)
local currentColor = pointPart.Color
local playerStats = player:WaitForChild("leaderstats")
local playerPoints = playerStats:WaitForChild("Points")
if currentColor == blue then
playerPoints.Value += smallPoints
end
end
```
2. To check for green, add an else if condition. If green, then add the `largePoints` variable to the player's points.
```lua
if currentColor == blue then
playerPoints.Value += smallPoints
elseif currentColor == green then
playerPoints.Value += largePoints
end
```
3. Use an else statement to subtract points if pointsPart was neither blue nor green.
```lua
if currentColor == blue then
playerPoints.Value += smallPoints
elseif currentColor == green then
playerPoints.Value += largePoints
else
playerPoints.Value -= losePoints
end
```
4. Lastly, **destroy** the part after the if statement so that the script can't keep giving out points.
```lua
if currentColor == blue then
playerPoints.Value += smallPoints
elseif currentColor == green then
playerPoints.Value += largePoints
else
playerPoints.Value -= losePoints
end
pointPart:Destroy()
```
5. Playtest and check that each color gives points as expected. Be sure to test all **three** conditions.
<video controls src="../../../assets/education/coding-3/colorPoint_showPointChange_web.mp4" width="100%"></video>
## Give players feedback
The PointPart works, but players might not notice something happened unless they happen to be looking at their leaderboard. Fix that by creating particles when the PointPart is destroyed.
Adding feedback when players use a part, like sounds, shakes, or particles, makes interactions with objects more satisfying to players.
<video controls src="../../../assets/education/coding-3/colorPoint_showParticles_web.mp4" width="100%"></video>
### Create a particle effect
The particle effect will be the same color as the part when touched. Since the colors were stored in variables, it's easy to reuse them.
1. In `givePoints()` at the bottom, create a new **ParticleEmitter** instance. Make sure the instance name is spelled exactly as shown.
```lua
local particle = Instance.new("ParticleEmitter")
end
```
2. ParticleEmitters use color sequences to control their Color property. Create a new ColorSequence and pass in the current part color.
```lua
-- Destroy part
pointPart:Destroy()
-- Create particles
local particle = Instance.new("ParticleEmitter")
particle.Color = ColorSequence.new(currentColor)
```
3. The particle will need to be parented to player that touched it. Create a variable to get the player's Character model. Then, parent the particle to the player's head.
```lua
local particle = Instance.new("ParticleEmitter")
particle.Color = ColorSequence.new(currentColor)
local playerCharacter = player.Character
particle.Parent = playerCharacter:WaitForChild("Head")
```
4. Use `Library.task.wait()` for a quick second, then destroy the particles.
```lua
local particle = Instance.new("ParticleEmitter")
particle.Color = ColorSequence.new(currentColor)
local playerCharacter = player.Character
particle.Parent = playerCharacter:WaitForChild("Head")
task.wait(1)
particle:Destroy()
```
5. Playtest the game and make sure particles briefly follow the player after touching each color.
<video controls src="../../../assets/education/coding-3/colorPoint_showParticles_web.mp4" width="100%"></video>
### Troubleshooting tips
At this point, if particles doesn't work as intended, try one of the following below.
- Make when creating a new instance that ParticleEmitter is spelled **exactly** as shown and inside quotations.
- When parenting the particles, make sure to use `:` between `playerCharacter` and `WaitForChild()` with no spaces between.
## Complete PointScript
A finished version of the script can be referenced below.
```lua
local pointPart = script.Parent
--local storage = game:GetService("ServerStorage")
-- Gives some points
local blue = Color3.fromRGB(0, 0, 255)
-- Gives more points
local green = Color3.fromRGB(0, 255, 0)
-- Makes players lose points
local red = Color3.fromRGB(255, 0, 0)
-- gold given to players
local smallPoints = 10
local largePoints = 50
local losePoints = 100
local Players = game:GetService("Players")
local function givePoints(player)
local currentColor = pointPart.Color
local playerStats = player:WaitForChild("leaderstats")
local playerPoints = playerStats:WaitForChild("Points")
-- Gives player gold based on the color of the part
if currentColor == blue then
playerPoints.Value += smallPoints
elseif currentColor == green then
playerPoints.Value += largePoints
else
playerPoints.Value -= losePoints
end
-- Destroy the part, wait a second, and then destroy the particle
pointPart:Destroy()
-- Creates a sparkles effect and destroys it
local playerCharacter = player.Character
local particle = Instance.new("ParticleEmitter")
particle.Color = ColorSequence.new(currentColor)
particle.Parent = playerCharacter:WaitForChild("Head")
task.wait(1)
particle:Destroy()
end
local function partTouched(otherPart)
local player = Players:GetPlayerFromCharacter(otherPart.Parent)
if player then
givePoints(player)
end
end
pointPart.Touched:Connect(partTouched)
-- Changes the color of the part based on variables. Needs to be at bottom of script.
while true do
pointPart.Color = blue
task.wait(4)
pointPart.Color = green
task.wait(3)
pointPart.Color = red
task.wait(2)
end
```

View file

@ -0,0 +1,163 @@
---
title: Intro to if statements
description: Learn how to code if statements in Luau.
next: /tutorials/fundamentals/coding-3/traps-with-if-statements
prev: /tutorials/fundamentals/coding-3/landing
---
In experiences, there are often many cause-and-effect relationships. For example:
- If a player scores 10 points, then they win the game.
- If a player has a power-up, then they can run super fast.
- If a player says "Happy Birthday" in chat, then confetti rains.
Scripts use conditional statements to handle these types of situations. **Conditional statements** are lines of code that only run if certain conditions are true. One type of conditional statement is an **if/then statement**. In Luau, the syntax pattern for if statements looks like this:
```lua title="if then syntax"
if "something happens" then
-- Make something else happen
end
```
Code chunks using conditionals are **control structures.** Control structures are like flow diagrams in code form and can have several conditional statements.
## If statement practice
These steps show how to create a script that changes a part's color if a statement is true.
1. In **ServerScriptService**, create a new script and name it `TruthChecker`. Add an appropriate comment to the script.
```lua
-- Changes the part if a condition is true
```
2. Create a new part named LieDetector.
### Format if statements
**Conditions** can come in various forms but are often simple statements like math equations. For example, if 1+1 equals 2, then run some code. Like ordinary math equations, conditional can use **operators** such as plus (`+`) or less than (`<`) to evaluate statements.
One particular operator to be aware of is `==`; it stands for "is equal to." So the statement `2 + 2 == 4` can be read as "two plus two is equal to four". Be very careful not to mix it up with `=`, which assigns new values to objects like variables.
1. Set up the empty conditional. In the script, type `if then`, and press <kbd>Enter</kbd> to autocomplete the conditional. The keyword `then` will be underlined because the code is incomplete.
```lua
if then
-- empty code
end
```
2. After the keyword `if`, type a true statement such as `3 + 3 == 6`.
```lua
if 3 + 3 == 6 then
-- empty code
end
```
3. Within the conditional, reference the part you named LieDetector and change the part's `Color` property to green.
```lua
if 3 + 3 == 6 then
workspace.LieDetector.Color = Color3.fromRGB(0, 255, 0)
end
```
<Alert severity="info">
Indenting the lines of code within the conditional makes it easier to see where the code chunk starts and stops.
</Alert>
4. **Test** your code. If three plus three is equal to six, the part will turn green.
## Check a false condition
Now, purposely change the statement to see what happens when the math equation is false.
1. In the if statement, change the equation to something inaccurate, such as `3 + 3 >= 10`.
```lua
if 3 + 3 >= 10 then
workspace.LieDetector.Color = Color3.fromRGB(0, 255, 0)
end
```
2. Test your code now. The part shouldn't turn green for a false statement.
### Math operators
The table below lists some common Luau operators. More information about operators can be found on [Luau Operators](../../../luau/operators.md).
<table>
<thead>
<tr>
<th>Symbol</th>
<th>Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td>`+`</td>
<td>Addition</td>
</tr>
<tr>
<td>`-`</td>
<td>Subtraction</td>
</tr>
<tr>
<td>`*`</td>
<td>Multiplication</td>
</tr>
<tr>
<td>`/`</td>
<td>Division</td>
</tr>
</tbody>
</table>
### Comparison operators
- `==` : Is equal to.
- `~=` : Is not equal to.
- `<` or `>` are used for less or greater than, respectively.
- `<=` or `>=` are used for less/greater than or equal to, respectively.
## Variables and properties
Conditional statements are also used to evaluate the status of properties and variables. The following steps check whether a variable was successfully assigned a value.
1. Delete all of the code and copy the following snippet into the script. Test it, and a new error appears in Output.
```lua
local mysteryPart = workspace.MysteryPart
-- Evaluates as true if MysteryPart was successfully assigned
if mysteryPart then
workspace.LieDetector.Color = Color3.fromRGB(0, 255, 0)
end
```
2. Insert a new part into the workspace named MysteryPart. Test again, and LieDetector should turn green.
3. Explore how properties can be evaluated with conditionals. Keep MysteryPart, but once again, delete your code and copy the code box below.
```lua
local mysteryPart = workspace.MysteryPart
-- Evaluates as true if MysteryPart is fully opaque
if mysteryPart.Transparency == 0 then
workspace.LieDetector.Color = Color3.fromRGB(0, 255, 0)
mysteryPart.Transparency = .2
end
```
4. Test the code, and if MysteryPart has the default transparency of 0, it will become ghostly while LieDetector turns green.
## Summary
Conditional statements check to see if a statement is accurate, and if so, run some code. If statements are a very common type of conditional statement. They use the pattern "If this is true, then do that."
Code chunks using conditional statements are called control structures. Control structures can hold multiple conditional statements.
In addition to evaluating if simple math statements are factual, conditionals are also used to check on the status of variables and properties.

View file

@ -0,0 +1,64 @@
---
title: Conditionals
description: A tutorial series on how to use if statements in Luau within Roblox Studio.
next: /tutorials/fundamentals/coding-3/intro-to-if-statements
prev: /tutorials/fundamentals/coding-2/multiple-parameters-and-arguments
---
### Series description
Many experiences have actions that only take place if a list of requirements are met. You may have seen rooms only specific teams could enter or inventory items only some players could purchase. This series will cover how to set up code that says, "If this happens, then do that."
### Objectives and prerequisites
<table>
<tbody>
<tr>
<td width="20%"><b>Learning Objectives</b></td>
<td>
Understand the logic behind `if` `then` statements and how to set up multiple scenarios with the keywords `elseif` and `else`.
</td>
</tr>
<tr>
<td><b>Prerequisites</b></td>
<td>
Before beginning this course, readers should be able to navigate Roblox Studio, as well as declare new variables and functions.
</td>
</tr>
</tbody>
</table>
### Series contents
<table>
<thead>
<tr>
<th>Article</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>[Intro to If Statements](../coding-3/intro-to-if-statements.md)</td>
<td>Learn how if statements work and how to code them in Luau.</td>
</tr>
<tr>
<td>[If Statement Practice: Trap Parts](../coding-3/traps-with-if-statements.md)</td>
<td>Use conditionals to create better traps that only hurt avatars and humanoids.</td>
</tr>
<tr>
<td>[If Statement Practice: Power Ups](../coding-3/powerups-with-if-statements.md)</td>
<td>Practice using `if` statements and create a part that increases the players' walking speed.</td>
</tr>
<tr>
<td>[Multiple Conditions](../coding-3/multiple-conditions.md)</td>
<td>Design code that accounts for multiple scenarios with `else` and `elseif`.</td>
</tr>
<tr>
<td>[Multiple Conditions Practice: Awarding Points](../coding-3/give-points.md)</td>
<td>Use everything learned about conditionals to create a part that can award points to players.</td>
</tr>
</tbody>
</table>

View file

@ -0,0 +1,353 @@
---
title: Multiple conditions
description: Learn how to use elseif and else to create more complex control structures in Luau.
next: /tutorials/fundamentals/coding-3/give-points
prev: /tutorials/fundamentals/coding-3/powerups-with-if-statements
---
Control structures can have more than one condition. The keywords `else` and `elseif` can create additional scenarios for what should happen under several conditions. The syntax looks like:
```lua title="Shows syntax for elseif and else"
if isGreen then
print("Go")
elseif isYellow then
print("Slow")
elseif isPedestrians then
print("Wait")
else
print("stop")
end
```
In this project, `else` and `elseif` are used to code a parkour course where runners receive awards depending on their finishing time.
<img src="../../../assets/education/coding-3/coding3Hero_ifElseIf.jpg" width="80%" />
## Code multiple conditions
For this project, you could write a unique if statement for each medal to award players, but that takes a lot of time. Take, for instance, the imaginary code below.
```lua title="All if statements"
if finishTime < 5 then
-- Get a gold medal
end
if finishTime >= 5 and <= 10 then
-- Get a silver medal
end
if finishTime > 10 and <= 15 then
-- Get a bronze medal
end
```
A more readable and efficient way to code this is to use a single if statement and use the keyword `elseif` to provide alternative conditions to test if the previous conditions aren't true.
```lua title="Uses elseif and else"
if finishTime < 5 then
-- Get a gold medal
elseif finishTime >= 5 and <= 10 then
-- Get a silver medal
elseif finishTime > 10 and <= 15 then
-- Get a bronze medal
end
```
When the if/then statement runs, it'll start at the top and only run the code for the **first** true condition it finds.
## Set up the race course
Start by placing the course's starting point and finish line, and then create a script to time the player and award different medals.
1. Create an anchored part named FinishLine. To make testing faster, place the start and end close together. You can move the finish line after finishing the script.
<GridContainer numColumns="2">
<figure>
<img src="../../../assets/education/coding-3/raceCourse_showPartCraeted.jpg" />
<figcaption>Finish Part</figcaption>
</figure>
<figure>
<img src="../../../assets/education/coding-3/raceCourse_showDistanceBetween.jpg" />
<figcaption>Entire Course</figcaption>
</figure>
</GridContainer>
2. In FinishLine, insert a script named RaceManager. Then, add one variable to store how many seconds have passed since the race started and a second variable to reference FinishLine.
```lua
local finishLine = script.Parent
local timePassed = 0
```
3. Create a function named `finish()`.
```lua
local timePassed = 0
local finishLine = script.Parent
local function finish()
end
```
4. On your own:
- Code a function named `partTouched()` that runs `finish()` when a player touches it.
- Connect the finish line part to `partTouched()`.
- Compare your code to the example below.
```lua
local function finish()
print("touched the finish line")
end
local function partTouched(otherPart)
local character = otherPart.Parent
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
if humanoid then
finish()
end
end
finishLine.Touched:Connect(partTouched)
```
5. Playtest and check that `finish()` is called when you touch the finish line.
### Keep finish() from repeating
Right now, whenever a player touches the finish line, `finish()` gets continuously called as long as the player touches the part.
Use a **boolean**, a variable that stores true or false, to ensure that finish() is only called once.
1. Create a new variable named `raceActive` and set it to `true`.
```lua
local timePassed = 0
local finishLine = script.Parent
local raceActive = true
-- Runs whenever the player touches the finish line part
local function finish()
```
2. Add a second condition to the if statement to check if raceActive is true before calling `finish()`.
```lua
local function partTouched(otherPart)
local character = otherPart.Parent
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
if humanoid and raceActive == true then
finish()
end
end
```
3. To stop `finish()` from being called again, set `raceActive` to `false`.
```lua
local function finish()
print("touched the finish line")
raceActive = false
end
```
4. Playtest your experience to check that you only see your test print statement once.
### Keep track of time
Like an if statement, a while loop can also use a condition to see if it should run. To time the player, create a timer using a while true do loop that only runs when the `raceActive` boolean is true.
1. At the bottom of the script, type `while raceActive == true do`. Press Enter to auto-complete and add the `end`.
```lua
finishLine.Touched:Connect(partTouched)
while raceActive == true do
end
```
<Alert severity="info">
Make sure the loop is at the **bottom** of the script. Even though this while true do loop, eventually stops, it should still stay at the bottom of the script. This ensures that the previous code runs before it reaches the loop.
</Alert>
2. To time the players, in the loop, add 1 to the `timePassed` variable once every second. Include a print statement to test your work.
```lua
finishLine.Touched:Connect(partTouched)
while raceActive == true do
task.wait(1)
timePassed += 1
print(timePassed)
end
```
3. Playtest the experience and check that you see each second displayed in the **Output** window.
## Award player medals
To finish, use an if statement with multiple conditions to award players a different prize medal based on their performance. Use an if statement and two elseif statements to check the player's finish time and award them the correct medal.
1. To confirm each medal can be awarded, use print statements.
```lua
local function finish()
raceActive = false
print("You finished in " .. timePassed)
end
```
2. To award a gold medal, code an if statement that compares `timePassed` to the desired finish time. This example checks if the player's time was less than or equal to 10 seconds.
```lua
local function finish()
raceActive = false
print("You finished in " .. timePassed)
if timePassed <= 10 then
print("You get a gold medal!")
end
end
```
3. Playtest and confirm the gold medal can be awarded.
### Add additional conditions
Now that you've tested for the gold medal, code conditions for the other medals using the `elseif` keyword.
1. For the silver medal, use `elseif` and the next desired time range. In this example, the range is greater than 10 seconds but less than or equal to 20 seconds.
```lua
local function finish()
raceActive = false
print("You finished in " .. timePassed)
if timePassed <= 10 then
print("You get a gold medal!")
elseif timePassed > 10 and timePassed <= 20 then
print("You get a silver medal!")
end
end
```
2. Use the same pattern for the bronze medal. Check your code with the example below.
```lua
local function finish()
raceActive = false
print("You finished in " .. timePassed)
if timePassed <= 10 then
print("You get a gold medal!")
elseif timePassed > 10 and timePassed <= 20 then
print("You get a silver medal!")
elseif timePassed > 20 and timePassed <= 30 then
print("You get a bronze medal!")
end
end
```
3. Playtest for the silver and bronze medals.
### Troubleshooting tips
If you don't see the silver and bronze metals appear, try one of the below.
- Each `elseif` should have a then after its condition.
- In `partTouched()`, make sure the second condition of the if statement uses `==`, like in `raceActive == true`.
- Check that each `elseif` is in scope. Each `elseif` condition must be between the first line of the if/then statement and it's last `end`.
### Add the else condition
If the player didn't earn any of the medals, you should encourage them to try again. In this case, you can use an `else` statement, which runs if **no other** conditions are true, to show them a message.
<Alert severity="info">
It's recommended that every if statement has an else, just in case the code doesn't find anything true.
</Alert>
1. Below the last `elseif` and above `end`, start a new line and type `else`. **Do not** add then. Beneath else, use a print statement to prompt them to try again.
```lua
local function finish()
raceActive = false
print("You finished in " .. timePassed)
if timePassed <= 10 then
print("You get a gold medal!")
elseif timePassed > 10 and timePassed <= 20 then
print("You get a silver medal!")
elseif timePassed > 20 and timePassed <= 30 then
print("You get a bronze medal!")
else
print("Try again!")
end
end
```
<Alert severity="info">
An `else` statement should always be the **last** check in an a control structure.
</Alert>
2 . Playtest to see the else message.
## Summary
Control structures can have more than one scenario. Use if statements to set up the initial statement to check, and then add as many `elseif` conditions as necessary. Finally, use `else` to state what should happen if all given conditions are false.
Starting at the top, all conditions will be checked, and only the first true condition will run the code. The remaining conditions will not be checked, nor will their code run.
After finishing the project, you can expand upon the script to add new elements in a few extra ways.
- Add code so players can repeat the race by touching the start line when they finish.
- Design a way to display time during a race. You can either display the time on a part using a Surface GUI, like in the
[Create a Timed Bridge tutorial](../coding-4/create-a-timed-bridge.md).
```lua title ="Completed script"
local timePassed = 0
local finishLine = script.Parent
-- Used to keep finish() and timer from repeating when race is over
local raceActive = true
-- Runs when the player touches the finish line and shows them an award
local function finish()
raceActive = false
print("You finished in " .. timePassed)
if timePassed <= 10 then
print("You get a gold medal!")
elseif timePassed > 10 and timePassed <= 20 then
print("You get a silver medal!")
elseif timePassed > 20 and timePassed <= 30 then
print("You get a bronze medal!")
else
print("Try again!")
end
end
-- Checks if a player touches the part when a race is active
local function partTouched(otherPart)
local character = otherPart.Parent
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
if humanoid and raceActive == true then
finish()
end
end
finishLine.Touched:Connect(partTouched)
-- Keeps track of race time while the race is active. Needs to be at script bottom.
while raceActive == true do
task.wait(1)
timePassed += 1
print(timePassed)
end
```

View file

@ -0,0 +1,140 @@
---
title: Evaluate multiple statements
description: How to use the and keyword to evaluate more than one statement at a time in Roblox Luau.
next: /tutorials/fundamentals/coding-3/multiple-conditions
prev: /tutorials/fundamentals/coding-3/traps-with-if-statements
---
If statements can have multiple requirements that need to be true before running code. The keyword `and` allows you to combine statements. The following code evaluates first if two plus two equals six and then if four does not equal six. If both statements are true, the code will run.
```lua
-- will not run
if 2 + 2 == 6 and 4 ~= 6 then
print("Both statements are true")
end
-- will run
if 4 + 2 == 6 and 4 ~= 6 then
print("Both statements are true")
end
```
## Create a powerup
Powerups are in-experience items that give players special abilities like flying, invisibility, or speed. This powerup will boost the player's walking speed every time the powerup is touched. Continuously applying boosts can make the player go way too fast, so `and` will be used to control the upper walking speed limit.
### Set up the powerup
Use this code with a simple part or a model, such as a crystal, coin, or glowing neon orb.
1. Create a new part named **Powerup** and insert a script named **WalkSpeedManager**.
2. Declare a variable named `speedBoost` and assign the script's parent object.
```lua
-- Gives a temporary speed boost when touched
local speedBoost = script.Parent
```
3. Set up a function named `onTouch` and connect it to the parent object's `Touched` event. Then playtest and check your work.
```lua
local speedBoost = script.Parent
local function onTouch(otherPart)
print("Something touched speedBoost")
end
speedBoost.Touched:Connect(onTouch)
```
4. The WalkSpeed property is found on Humanoid objects. Use the same pattern used when creating a trap part and create a conditional that checks for Humanoid objects.
```lua title="Looks for Humanoid parts"
local function onTouch(otherPart)
local character = otherPart.Parent
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
if humanoid then
print("A Humanoid was found")
end
end
```
## Speed players up
The speed boost will make avatars walk faster every time the speed boost is touched. That will quickly become very, very fast. The keyword `and` will ensure players can't go too fast by only enabling the speed boost if the player is under a certain speed.
1. If a Humanoid is found, take the current WalkSpeed value and add 10 to it. Playtest, and your avatar will get faster every time it touches the speed boost.
```lua title="Increases current WalkSpeed"
local function onTouch(otherPart)
local character = otherPart.Parent
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
if humanoid then
humanoid.WalkSpeed += 10
end
end
speedBoost.Touched:Connect(onTouch)
```
2. In the if statement, use the keyword `and` to add a second condition that the current WalkSpeed value is less than 50. After adding the boost, the fastest WalkSpeed value will be 60.
```lua title="Checks if current WalkSpeed is 50 or less"
if humanoid and humanoid.WalkSpeed <= 50 then
humanoid.WalkSpeed += 10
end
```
### Fine tune the speed boost
OnTouch is called every time the speed boost is touched. Every step or slightest bounce triggers the Touched event and calls the connected function. The part's property, `CanTouch` can keep the Touched event from firing. Take advantage of CanTouch and turn off the speed boost for one second every time it's been activated.
1. After applying the boost, set the part's CanTouch property to false. Playtest and make sure the boost only applies once.
```lua title="Disables the speed boost"
local speedBoost = script.Parent
local function onTouch(otherPart)
local character = otherPart.Parent
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
if humanoid and humanoid.WalkSpeed <= 50 then
humanoid.WalkSpeed += 10
speedBoost.CanTouch = false
end
end
speedBoost.Touched:Connect(onTouch)
```
2. Use `task.wait(1)` to pause the script for one second, then set CanTouch to true. Playtest and make sure the speed boost can be reapplied after one second.
```lua title="Finished script"
local speedBoost = script.Parent
local function onTouch(otherPart)
local character = otherPart.Parent
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
if humanoid and humanoid.WalkSpeed <= 50 then
humanoid.WalkSpeed += 10
speedBoost.CanTouch = false
task.wait(1)
speedBoost.CanTouch = true
end
end
speedBoost.Touched:Connect(onTouch)
```
3. Play with the values in the finished script. WalkSpeed can go up to 100. The default WalkSpeed value is 16.
## Summary
The keyword `and` can be used to require multiple conditions before running a code chunk, such as a value being more than 0 and less than 100. Or that if there is a Humanoid and its WalkSpeed is less or equal to 50.

View file

@ -0,0 +1,163 @@
---
title: If/then practice with traps
description: Create a trap that sets the player's health to zero with Luau.
next: /tutorials/fundamentals/coding-3/powerups-with-if-statements
prev: /tutorials/fundamentals/coding-3/intro-to-if-statements
---
Traps that decrease players' health are a fun game-play element that can be coded with conditional statements. Practice using conditionals by creating a part that sets the player's health to zero when touched.
<video controls src="../../../assets/education/coding-3/trap-exampleFinal.mp4" width="80%"></video>
## Set up the trap
Traps work exceptionally well in experiences with movement-based challenges, like obbies. These steps will start by setting up the necessary variables and functions. Do as much as you can without looking at the code boxes first.
1. Create and name a trap part. Insert a script into the part.
2. In the script, add a descriptive comment and then use a variable to reference the script's parent.
```lua
-- If a player touches this part, set their health to 0
local trapPart = script.Parent
```
3. Create a function named `onTouch()` with a parameter named `otherPart`.
```lua
-- If a player touches this part, set their health to 0
local trapPart = script.Parent
local function onTouch(otherPart)
end
```
4. Connect the function to the trap part's `Touched` event to run whenever something touches the part.
```lua
local trapPart = script.Parent
local function onTouch(otherPart)
end
trapPart.Touched:Connect(onTouch)
```
## Check for player touch
Remember, the parameter `otherPart` records whatever touches the trap part, which might be a part of a player or just the baseplate.
To ensure the trap will only destroy players and won't destroy random decor items, use an if/then statement to check if whatever is in `otherPart` contains a Humanoid object.
<Alert severity="info">
Humanoids are present in player avatars and many NPCs. Humanoids have several unique properties. One such property is Health.
</Alert>
### Find a specific object
The function `FindFirstChildWhichIsA()` can be used to look for specific object types, which is handy because we're looking for a Humanoid-type object. Players will likely touch the trap with only a part of their avatar, so a variable must be set up to find the parent of the touching part and search it for a Humanoid.
1. In `onTouch()`, type `local character = otherPart.Parent`.
```lua
local trapPart = script.Parent
local function onTouch(otherPart)
-- Finds otherPart's parent object
local character = otherPart.Parent
end
trapPart.Touched:Connect(onTouch)
```
2. Check to see if `character` has a `Class.Humanoid` by typing:
`local humanoid = character:FindFirstChildWhichIsA("Humanoid")`
```lua
local trapPart = script.Parent
local function onTouch(otherPart)
local character = otherPart.Parent
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
end
trapPart.Touched:Connect(onTouch)
```
### Check with an if statement
If a Humanoid is found, then set the Humanoid's Health to zero.
1. Use an if statement to check if a Humanoid was successfully assigned to `local humanoid`.
```lua
local trapPart = script.Parent
local function onTouch(otherPart)
local character = otherPart.Parent
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
-- Evaluates if a Humanoid was found
if humanoid then
end
end
trapPart.Touched:Connect(onTouch)
```
2. Add a print statement and check the code so far.
```lua
local trapPart = script.Parent
local function onTouch(otherPart)
local character = otherPart.Parent
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
-- Evaluates if a Humanoid was found
if humanoid then
print("Found a Humanoid")
end
end
trapPart.Touched:Connect(onTouch)
```
3. **Run** the code and check that you can see the output whenever a player touches the part.
## Change the player's health
If the statement is true, you can use the same humanoid variable to set the player's health to 0.
1. Between `then` and `end`, type `humanoid.Health = 0`.
```lua title="Completed script"
local trapPart = script.Parent
local function onTouch(otherPart)
local character = otherPart.Parent
local humanoid = character:FindFirstChildWhichIsA("Humanoid")
-- Evaluates if a Humanoid was found
if humanoid then
print("Found a Humanoid")
humanoid.Health = 0
end
end
trapPart.Touched:Connect(onTouch)
```
2. Test the trap.
## Summary
This trap part used conditionals to detect Humanoid parts and set the Humanoid's health to zero. This script is an improvement on the previous trap script, which destroyed any touching object no matter what it was.
It does, however, still have a few flaws. Humanoids aren't just in players. Humanoids are also found in non-playable characters. The script is also only good at setting the player's health to zero. You can experiment with subtracting a small amount of health, but it's likely to subtract the health faster than desired. Later lessons provide further improvements to give greater control over how much health is subtracted from players.