Welcome to my Scripting Tutorial, i’ll expand it overtime, for now, let’s get started
About me
Hello, i’m Ideal, i code in Roblox for 7 years now and i wanted to share my knowledge
When i started, there were no tutorials in my language (I’m Polish) apart of few very basic ones, i really like how the roblox changed, and this time there are tutorials, including this one
Before we start, i dedicate this tutorial to my friend, Apro87 who is beginner and needs that help
Tutorials List:
A) Lua basics
- Before we start
- Variables
- Operators&Basic math
- Conditional Statements
- Functions
- Loops
- For loop
- Tables
- Math library
- Basic Code Organisation
- Types
B) Roblox’s Api
- Instances and their methoods
- Parts manipulation
- 3D Vectors
- Events
- Detectors
- CFrames
- Attributes
- Vector math: Linear Interpolation
- Services
- Enums
- Filtering: Client vs Server
- Introduction to local scripts
- Basic gui programming
- Tween Service - Better lerping
- Client and Server rules
- Tools
- User Input Service - Detecting key presses
- Run Service - Physical simulations & smooth movement
- Remotes & Bindables - Scripts connection
- Modular scripting
- Data Storage - Saving stuff
- PCalls - Safe functions
- Teleport Service - Teleportation between places
- Raycasting - Advanced collision detection
- Micro Modules - Code sorting strategy
- OOP - Code organisation strategy
- Collection Service - Game optimization
- Tips and advices about coding
Now, let’s begin our jorney!
Lua basics
1. Before we start
Soo, before we start, you need to know how to use Roblox Studio, and how Explorer and Propertiess works!
If you are 100% sure that you meet those requirements, then, let’s start
First of all, we need to do 2 things, first is to insert new script, for now we will put them in workspace to make it simple
Second thing is to open Output tab, it’s console where we can write messages using scripts
To open output navigate to VIEW section and then find Output it’s near explorer and propertiess
When we have everything ready, we can start coding by opening our Script
You should see:
print("Hello world!")
What is this? you may ask, let’s Run our game to see what will happen
as you can see, there is "Hello world!" message on the output
Print methood is using to output any text, as long as it’s inside quotes, there is also Warn methood that works the same, the difference is the color of text will be orange
warn("There is an error!")
Both methoods are very usefull, Prints and Warns can be used for debugging, analysing other scripts, testing and many more things
Apart of those two methoods that you learned, i want to show you another very usefull thing, Comments
-- this is single-line comment
--[[
this is multi-line comment
]]
Comments are part of your script that can’t be read by machine, soo you can use them to safely describe what each section does, they allows you to make your code cleaner and more sorted
The last thing, always remember about Upper-Case letters, one letter can make very, i mean very big mistake!
Thanks for reading first part
2. Variables
Welcome to second tutorial, today we will learn about Variables
What are they? what they are used for?
Variables are containers of data, there are few types of data, we will talk about them in a moment, first, how to create a Variable?
local var
local is key that allows us to define variable, in this case we named our Variable “var”,
it can be made from any normal letters, remember that Variables must have unique names!!!
Yea, Variables must have unique name, otherwise they will be Overwritten
Overwrite is situation when we change our Variable’s current value to other value
Yea, but what are those values are???
Values are some type of data that Variable holds, there are few common types:
- Number
- String (Text)
- Boolean (true/false)
- Object (other Roblox object)
- Table
Now, when we know our types, we can make real Variables
local NumberA = 5 -- Number
local Text = "Hello everyone!" -- String
local Debounce = true -- Boolean
local Part = workspace.Part -- Roblox's object
local Pets = {} -- Table
As you can see, this is how we create our Variable
Then how to overwrite it???
It’s as simple as creation of one, here’s how:
local Number = 5 -- number variable
Number = 7 -- we change Number's value to 7
One last thing, we can create empty variables, their type is nil
local target -- empty variable, it can be assigned
--[[Some code...]]
target = Dog -- after some code we can assign target to other Variable or Object
alternatively, we can set current variable to empty one
local Part = workspace.Part -- Variable that stores Object
--[[Some code...]]
Part = nil
Note: Those --[[Some code...]] comments are only to replace real code, soo showcase would look better
Thanks, this was all for today’s tutorial, have a nice day! Godbye!
3. Operators&Basic math
Welcome to next tutorial, today we will take look at Operators and Basics of math, let’s start!
When we know that Variables can be Overwritten and also assigned to other Variable, we can start doing some real things with them
local a = 5
local b = 3
We have two numbers, and we want to get third number that will be Sum of a and b
How we can achieve that???
This is where Operators come to help us, they are Mathematical symbols that performs some operation on numbers or other objects
local a = 5
local b = 3
local c = a + b
print(c)
When you will Run the game, on the output, value of c will show
there are 5 most used mathematical operators:
(+) addition
(-) subtraction
(*) multiplication
(/) division
(%) modulo - reminder of division
Changing Variable by it’s own value, it’s very usefull when we want to create some Coins system or shop where we take only specific amount of Player’s currency
local PlayerCoins = Player.Coins-- number of coins player currently have
local ItemPrice = 400
--[[We detect when player purchases an item]]
PlayerCoins.Value = PlayerCoins.Value - ItemPrice
This will decrease value of Coins by 400
Eventually you can make it shorter:
PlayerCoins.Value -= ItemPrice -- works the same, simply shorter
You can do that with any of operators mentioned above
It’s everything today, Thanks for reading, Godbye!
4. Conditional Statements
Welcome, today we will learn Conditional Statements
what are they? and what they do?
you will see in a moment :}
Soo, before we start, we need to know what Logic Gates are, they are common in games and they are important part of computer building, in Roblox, we have 3 main gates:
- Or Gate
- Not Gate
- And Gate
You may ask, what they do?
Logic gates are used to compare if more advanced Condition is True or False
But first, we need talk about Conditions
local a = 5
local b = 3
local c = a + b
Let's say we have to check if number c is 8 or not, this is how we can do this
local a = 5
local b = 3
local c = a + b == 8
print(c)
If you run this code, you will get True, try to change a or b and you will get False
As you can see, after our equation there are two equals signs
Yes, there are two equal signs, because it’s Condition, double equal sign symbol is equation statement, it’s also boolean, soo we can have True or False
There are few other logic operators:
(>) a greater than b
(<) a smaller than b
(>=) a greater or equal b
(<=) a smaller or equal b
(~=) a is not equal to b
Also, we can create more advanced statements, with help of our Logic Gates
local a = 4
local b = 3
local c = 2
local d = 1
local e = a + b >= 5 and c + d ~= 3
print(e)
Run the game, if a + b is greater or equal 5 and c + d is not equal 3, then it will return True
As you can see, we combined two statements using Logic Gate this is very usefull, we can make checks with this, but there is one thing that will connect all of it
local a = 4
local b = 3
local c = 2
local d = 1
local e = a + b >= 5 and c + d ~= 3
if e then
print("Our equation is correct")
else
print("Sadly, our equation is incorrect")
end
What are this??? what are ends, and those if thing???
Great question, soo i’ll provide answer, If Statement is lua element, that allows us to control the flow of information, this mean, we can detect if something is correct and then run code depending on situation
This second statement, Else is usually used alongside with If, it runs it’s code when every statement above failed
We can also add ElseIf to control more situations
local a = 5
local b = 3
local c = 2
if a + b > c then
print("a + b is greater than c")
elseif a - c == b then
print("a - c is equal to b")
else
print("probably other scenario")
end
You can observe that code runs in specific order, from top to bottom, every statement is considered after another's fail, remember that
IMPORTANT NOTE: to make your code redable, inside every If Statement code should be moved by pressing TAB key, this will make your code look a lot better!
At the end, i want to add that you should always take look at those namings and other stuff like that, it’s very easy to make mistake, luckily Output and Print methoods will help you with debbuging
you can place Prints before each If Statement to check when code failed, and try to fix it
This was all for today, thank you for your attention, have a nice day!
5. Functions
Welcome everyone, today we will learn about Functions
I’m sure that most of you had functions in math classes, if not, don’t worry, in Lua functions are completely different
But what are they?
Functions are part of code that have some task, usually they are tools that you use to optimize and simplify your code
function example()
print("Hey!")
end
example()
After running the game, you can see "Hey!" on the output
Soo, what this Function does? it simply print some text
Therefore, you can use Functions to make your code more redable, but what about using them as tools?
function getSpeed(Street:number,Time:number):number
return Street/Time
end
local CarSpeed = getSpeed(40,20)
print(CarSpeed)
After running game, we will see 2 units of speed, because in 20 seconds, we travelled 40 units of distance
Note: I used this strange :number
, those are types, you can use them to make your code more cleaner, you can put many things there, for now you don’t need this
First, talk about this Function’s structure, it have Name that we call, it have Arguments inside brackets, and Return value which is optional, sometimes we give some Arguments only to make function use them to complete it’s task
Outside of function, we made new Variable and we Called Function, we gave Arguments
and printed the Return value
Sometimes we can use local functions, if we don’t have to use Function in other Function or Line above it, here is cleaner example:
Hello() -- function can be called in lines above it's first creation
--[[we mention our function for the first time]]
function Hello()
print("Hello everyone!")
end
Hello() -- it will give an error, local function can't be called outside it's scope
local function Hello()
print("Hello everyone!")
end
Hello() -- will be Ok, function is called after it was defined in this scope
Soo, now you know what is difference between local and normal functions, you should use both of them, but in specific situation, one is better than the other
Note: Scopes are parts of code that share their variables, If Statement is great example of scope, everything between Statement and End is scope
Today we learned about very usefull component, before we end
Exercise:
Create function that checks if given power is too low, good or too high and return if it can be used safely or not
Thanks for today, have a nice day, Godbye!
6. Loops
Welcome, today we will learn about Loops, this is part 1 of this tutorial
First, theory
For now, you could call something once, before it will turn into 1000 lines of “Hello world!” prints, now we will meet Loops they, as the name suggests, they repeat code inside of them
IMPORTANT NOTE:
task.wait(1/10) -- roblox api methood that allows us to wait x seconds before executing code
If we don’t want to make our computer explode, put this before End in every loop, it even can be 0 seconds, but it have to be there
There are 3 basic lua loops:
- For loop
- Repeat loop
- While loop
while true do
print("Infinite loop!")
task.wait(1)
end
While loop is infinite loop, that will run to the point when statement(true in this case is infinite) will change to false
local a = 5
local b = 3
while a + b > 20 do
print("Still running...")
a += 1
task.wait(0)
end
Loop will run about 12 times before statement will be False, then it will stop
At the end, While Loop is loop that repeats code until it’s statement will become False
But now, if While Loops are infinite, then what repeat loops are?
Repeat loop is almost the same,
ALMOST!!!
local a = 5
local b = 3
repeat
print("Hi")
a += 1
until a + b > 20
It will run the code until statement will be True
But, it’s the same as While Loop! only inverted!
Not exacly, in While Loops statement is checked before running code
On the other hand, Repeat Loop will always run code at least once, before it’s statement will become True and break the loop
Last thing, one keyworld that will help you a lot
while True do
print("Nothing happened")
if SomeThingHappened == true then
print("Something happened!")
break
end
task.wait(1)
end
break keyworld ends the loop, you can’t write anything in scope after it, break ends the loop
Now you should practice your coding, in next part we will consider more advanced topics!
Thanks for today, soon i’ll create part 2 of this tutorial, for now have a nice day, Godbye!
7. For loops
Welcome, today we will learn about For Loops it’s part 2 of previous tutorial, soo read it before this one, let’s begin
You know that Loops allows us to repeat code inside them, but only if the statement of the loop is True or False depending on loop’s type
For Loop is different, it’s statement is not True or False, it’s rather pre-defined
For Loop is loop that repeats x number of times and then stops, it doesn’t require you to break it or change conditions
for i = 1, 10 do
print(i) -- will print numbers from 1 to 10, i is loop counter that changes every time loop runs code
end
But what it does??? it doesn't look like previous ones
Yea, this is the case why it’s part 2
This type of loop have one variable, it’s loop counter, the most common name of it is “i” or “_” but you can use any String for that, still those 2 are the best to use
loop counter changes every time, it can grow or decrease, we can also change default value of growth (it’s 1) to any that we want
for i = 1, 10, -1 do
print(i) -- will print numbers from 10 to 1
end
Note: For clear explanation, third argument (in case above -1) is optional, default value is 1
for i = 0, 1, 0.1 do
print(i) -- will print fractions from 0 to 1, it's step is 0.1 soo 0.1,0.2,0.3...
end
Note: In for loops you usually don’t need to add task.wait()
because they are not infinite
Ok, soo if For Loop is used to repeat things X times, and it changes it's counter, where we can use it???
For Loop is interestingly the mostly used loop in entire Roblox, it’s used alongside with Tables to create data structures and frameworks
For Loop is heavily connected to Tables, we will consider them in third part of this tutorial
Thanks for reading, have a nice day!
8. Tables
Welcome, today we will learn about Tables, this is third and the last part of loops tutorial
When we know what For Loop does, as it counts numbers and repeats code X times, we can use this to our advantage, see Tables are simply sorted lists of Variables
What does it mean???
Tables are lists of elements, those elements have 2 propertiess:
Key & Value
local arr = {
[1] = 5,
[2] = 3,
[3] = 4
}
print(arr) -- will print {...} that can be expanded, then you can see table's **Keys** and **Values**
What??? this is the strangest thing ever!
Maybe it looks like, but, it’s pretty simple, Tables holds elements, those elements have Key that is position where element’s Value is assigned
Note: you don’t have to write those numbers in [ ], Lua will automatically add Keys to Values like this:
local arr = {
5, -- Key is 1
4, -- Key is 2
3 -- Key is 3
}
Note: Keys can be represented as Strings, then table behaves like an array, remember that there can be only one Key with the same number | name
local arr = {
[1] = 5,
[1] = 3, -- will throw an error!!!!
[2] = 2
}
--[[Keys can be represented as Strings, below see example of table that stores fruit counts]]
local fruits = {
["Oranges"] = 5,
["Apples"] = 3,
["Lemons"] = 4
print(fruits)
}
Now we will learn how to manipulate Tables
First, there is library for that in Roblox, but it’s usually better to use other methoods to make your code more efficient
One of those methoods is indexing, indexing is simply assigning Keys to Values
local arr = {} -- empty array (table with keys&values)
arr[1] = 5 -- we assign value of 5 to key number 1
arr[2] = 4
arr[3] = 2
print(arr)
We can index with Strings
local arr = {} -- empty array
arr["Oranges"] = 5 -- we assign value of 5 to key that represents Oranges
arr["Apples"] = 3
print(arr) -- prints our list of fruits on the output
print(arr["Oranges"]) -- will print Value of this Oranges
After all of those things with tables, can we do something else?
Yes of course
Now we will meet new type of loop
For Loops as you know have counter that changes every time it runs, and tables can have numerical Keys, we can connect both of them to read all Values using For Loop
local arr = {
"Apple",
"Pear",
"Lemon",
"Orange",
"Cherry"
}
for i = 1,5 do
local Fruit = arr[i] -- every time fruit will be the same as our array's values
print(Fruit) -- Apple, Pear, Lemon, Orange, Cherry
task.wait(1)
end
Run the code and you'll see that every 1 second a different fruit name is printed, the same as in array's order
Is there any option to make this shorter???
Yes, a little bit, it’s where new type of Foor Loop comes in handy
local arr = {
"Red",
"Blue",
"Yellow"
}
for i, Color in arr do
print(i,Color) -- prints Key which is named "i" and Color
end
After running the game, you can see that it printed number and then color
For in loop repeats it's code for each table elements, if there are 50 elements, there will be 50 repeats, if there are 1000 elements, there will be 1000 repeats and soo on
To show you better example, i added String Keys in place of numbers
local arr = {
["Color1"] = "Red",
["Color2"] = "Blue",
["Color3"] = "Yellow"
}
for i, Color in arr do
print(i,Color)
end
As you can see, "i" is now name and it's printed like order in our array
To end this, i want to add that there are two tricks to make your life easier
First, if you want remove something from table, simply make:
arr[Key] = nil -- assigns Value of nil to Key, soo table removes this Key
arr[Key] = newValue -- also you can overwrite Key's Value
IMPORTANT NOTE: For next trick, you can assign Key’s Value to 1 if you need something to be checked but not used is usually stored as key, soo it can be easily checked
Second, is how to detect if some object is present or not
For cleaner explanation, let’s say we have Players list that contains player’s nick as Key that are inside round, and we want to perform some action, but only if player is playing
To do that we can use arrays with Keys only! in this type of array, every key have Value of 1 because Value is not important in this case
local Players = {
}
--[[Some code that adds players in game]]
--[[Some event that calls function to check if player is in game]]
if Players[Player.Name] then -- checks if Player's name is on the list
return true
else
return false
end
Why is this methood good???
Trying to find if Table have some Key or not is easier for computer than looping through entire array and searching if value is present, also Value of 1 that is not used is very small amount of data, almost nothing
Soo to summarize everything:
- Loops are piece of code that repeats some task, depending on loop it might be different how
- For Loops repeat code X times that was set by programmer
- Tables are lists of elements that contain Key and Value
- Key is identificator that can be used to find specific element’s Value inside table
- Keys can be either numbers or strings
- There is special For Loop that loops through every table’s element
- Loops can be breaked either by using break or by changing it’s Running Statement
- There is methood where we use only Keys to store data required to be checked if it’s there or not
Thank you very much for reading my tutorial about Loops and Tables, in next tutorial we will learn about math library and how to use it, have a nice day, Godbye!
9. Math library
Welcome, today we will learn about basic functions of math library
This time, it’s very short tutorial, math library allows you to perform more advanced mathematical operations
Before we will take look into few of them, there are 3 other operators that i didn’t mentioned:
(-) Unary minus, negates value in front of it
(^) Exponentation
(//) Floor division, Rounds result to nearest full number that is less or equal result
Ok, now we can start talking about library
Usually library is collection of methoods or functions provided by programming language or plugins, math library is Roblox’s collection of math functions
How to use it?
local SOMENUMBER = math.FUNCTION() -> Result
Above is example how to call it, in this case we want variable that is result of math library function
List of most used functions:
math.random(min,max)
> returns pseudo-random value between min and max numbers
math.rad(angle in degree)
> transforms degree to radians
math.deg(angle in radians)
> transforms radians to degree
math.abs(number)
> returns distance of number from 0
math.sign(number)
> returns -1, 0, 1 depending if number was positive, negative or equal zero
math.clamp(number,min,max)
> limits given number between min and max, and eventually changes to max if number is greater or to min if is less than given range
math.floor(number)
> rounds number to largest full number that is less than it
math.ceil(number)
> rounds number to smallest full number that is greater than it
math.round(number)
> rounds number with math rule (if number is less than 0.5, works like floor, if it’s greater or equal, then like ceil)
math.pow(number,power)
> works like number^power (2^2 = 4, 2^3 = 8, 2^4 = 16…)
math.sqrt(number)
> works like number^1/2
Trigonometry functions and Inverse Trigonometry functions
Apart of those methoods, there are few others, also there are 2 mathematical constants:
math.pi
> returns value of π
math.huge
> returns very huge number
Remember that i wanted to show you simplified version of the most common methoods, few describtions can be difficult for some people, if you want more explanation, then
all methoods can be found here: math | Documentation - Roblox Creator Hub
What can we use this library for?
There are variety of ways, many genres of games use them, here are few examples:
- Shooters
- Building games
- Vechicle games
- Minigames
and more!
Thanks for reading, have a nice day, Godbye!
10. Basic Code Organisation
Welcome, today we will learn about Code Organisation, those are tips from my experience, let’s start
Soo, comments are used to describe code, you can use them as decoration too, here’s some propositions:
local Model = script.Parent
local RunService = game:GetService("RunService")
local Debris = game:GetService("Debris")
local CollectionService = game:GetService("CollectionService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local remoteEvent = ReplicatedStorage.Remotes.Event
local remoteFunction = ReplicatedStorage.Remotes.Function
local Part = Model.Parts.Part -- very normal part
local Gun = Model.Weapons.Gun -- super new Blaster
--------------------------------------------------------------------------
--------------------------------------------------------------------------
--[[Function that does something]]
local someFunction = function(argument,number,car):{}
car.Position = Vector3.new(5,5,5)
argument += 2
number = argument * car.Position.X
return {number,number*2,argument*car.CFrame.LookVector}
end
--------------------------------------------------------------------------
--[[Function that register rocks]]
local function rock(rock,name):"new"
local new = name.." and "..rock
return new
end
Of course this function makes no sense, but it’s example, we use different symbols to make our code redable, we use headers and describtions to decorate our code, soo it’s clean
Also another very easy thing is to use TAB to move code to the right, as you can see, every scope have one Tab, this mean code inside function, will be moved, code inside loop inside function will be moved even further
local function Something()
for i = 1, 10 do
if i > 5 then
print("Hi")
else
print("Wait")
end -- scope 3
end -- scope 2
end -- scope 1
Apart of that, the hardest part, NAMING, for this i can’t really show example, simply try to name Functions, Variables, Objects and everything else depending on it’s functionality
For instance function that calculates bullet’s trajectory should be called CalculateBulletTrajectory
or maybe value of car’s speed should be called CarSpeed
, so it can be understood easily
Types are another thing that should be considered, more about them in next tutorial
Another quick thing, use space to separate important stuff, variables should be separated from objects, or stuff related to something specific should be separated from other things
This is more advanced tip, and also short, you can replace certain Roblox’s Api stuff with math, math is usually more efficient and use less performance, those are more specific cases and advanced topics, but keep that in mind
Follow good practices, you can find them on forum, here are some links:
IMPORTANT NOTE: Always be open to alternatives, roblox advances quickly, and adds new ways to make everything better
Those were few tips for making your code cleaner and better organised, you should use them to become better
Thanks for reading, have a nice day, Godbye!
11. Types
Welcome, today we will learn about Types, this is our last Lua tutorial
Soo, i used Types few times, they are simply what Type of thing is Variable
There are many types, i mentioned 4 basic ones:
- numbers
- booleans
- strings
- tables
There are of course tens of Roblox’s own Types like Instances, Parts, Constraints and more
Types are used to organise code and to describe specific variables, let’s say we want to make 10 different values required for system to run, and we want player who don’t know programming to change them, we simply add types and player will know what type of stuff to write in
local speed : number = 50
local isFuelInfinite : boolean = true
local carName : String = "Super car"
We can create our own custom types
type rock = Part -- custom types have to be equal currently existing ones
type custom = "Custom Type" -- using string type to create new type, usefull in some cases
Can we detect if object's type is equal to type that we looking for?
Yes, to do this we use typeOf methood
local part = workspace.Part
if typeOf(part) == "Part" then
print("Part is Part... what?")
end
Types can be used for some logic code or checks, but for the most time you will use them as visuals
Thanks for today, i believe i helped you learn Lua, i have Roblox’s Api tutorials in plan, stay tuned, have a nice day, Godbye!
Roblox’s Api
1. Instances and their methoods
Welcome, to our first intermediate coding tutorial, today i’ll show you first important Roblox’s api topic, Instances.
Also before we start, i thank you for reading my tutorials, i’m glad that i could help you learning
Soo, what are Instances? they are like variables, but they are physically present
There are hundreds of them in Roblox, Parts are one kind of them, Scripts are also Instances
Every object that was created inside Roblox’s explorer is Instance, they can be defined as variables in scripts, created or destroyed by them and manipulated to achieve perfect result
local Instance = workspace.Part -- workspace is place where we store Parts
As you can see we described some Instance as workspace.Part
What this script above means? this mean that our Instance is equal to workspace’s child called Part, and if every object inside explorer is Instance, this mean that this Part is in fact Instance
But what we can do if we defined Instance???
Great question, here is what we can do:
local Part = workspace.Part
Part.Color = Color3.new(20,90,71) -- we changed Part's color
local Clone = Part:Clone() -- we defined new Part by clonning previous
Clone.Parent = workspace -- we set new Part's parent to workspace
Part:Destroy() -- we removed part from the game
You can manipulate Parts using Instance’s methoods, or by changing it’s propertiess, you can find instance propertiess by using Propertiess tool in VIEW tab, then simply type:
Instance.Property = new property
There are few most commonly used methoods:
-
:Destroy()
-
:Clone()
-
:FindFirstChild(“name”) – finds other instance with the same name that’s Parent is our current instance
-
:WaitForChild(“name”) – finds other instance like FindFirstChild, but yields until it’s created
-
:GetChildren() – returns table of every child of this instance
There are many more methoods, but i didn’t mentioned all of them
Every other methood: Instance | Documentation - Roblox Creator Hub
Thanks for today, i believe i helped you understand what Instances are, have a nice day, Godbye!
2. Parts manipulation
Welcome, today we will learn about Parts, not in studio, but in programming
First of all, Part is an Instance, it’s used by builders, moddelers, almost every other developer
But what others can’t do is to manipulate it when game is running, today we will learn about how to change propertiess of a Part via script, you can do that with ANY Instance
local Part = Instance.new("Part") -- we create new Part
First of all we create new Part via Instance.new methood that we’ve learned in last tutorial, remember to always define only ClassName in this methood (ClassName is type of Instance like Part, MeshPart, Script ect.)
local Part = Instance.new("Part")
Part.Name = "New Part" -- Name is property of every Instance
Part.Archivable = true -- This is true automatically, i wanted to show it, it allows Instance to be cloned
Part.Anchored = true -- Set this to true if you don't need physics, or else it will glitch
Part.Transparency = 0.5
Part.Color = Color3.new(255,0,255) -- Color3 is used in GUI but also in parts
-- Many propertiess have 3 numbers, we can use libraries like Color, Vector or CFrame
-- Vectors are related to almost every 3D space property, only CFrames are more complex
Part.Size = Vector3.new(3,3,3)
Part.Position = Vector3.new(0,10,0)
Part.Orientation = Vector3.new(45,45,45)
Part.Shape = Enum.PartType.Ball -- Enum is collection of data in lua, we will talk about them later
-- Enum.PartType contains every Part's possible shape
Part.Parent = workspace -- Parent is where Instance belongs to, it's like putting part in workspace
I added few properties change above, you can check docs or Propertiess to know how to change specific ones
Docs: Part | Documentation - Roblox Creator Hub
We will talk about specific things that i showed in this tutorial later on
Thanks for reading, have a nice day, Godbye!
3. 3D Vectors
Welcome, today we will learn about Vector3
You may know from math classes what Vector is, in mathematical or physical meaning, it’s element that have direction and value, and of course usually represents forces
In Roblox, it’s the same, but here Vectors are used to place BaseParts and Models in 3D space
Of course you can use Vectors and math to create forces and more, but at this level of knowledge you will use them mostly for those 3 things:
- Placing object in 3D
- Scaling object in 3D
- Rotating object in 3D
Soo, how we can do this?
local Part = Instance.new("Part") -- we will work with part, it's easiest example
Part.Position = Vector3.new(X,Y,Z) -- Vector3 is vector library
Part.Parent = workspace
Why you wrote X,Y,Z instead of numbers???
I wrote that to show you that Vector is like coordinates, Position is a Vector in programming
And of course vector library is important here, this library allows us to create Vectors and other related stuff, usually you will use Vector3.new(X,Y,Z)
for 90% of your scripts, what it does is the same as Instance library, creates new object related to it, in this case: Vector
NOTE: Vector can be stored as Variable like almost every object in Roblox
When we know how to create Vectors, let’s say we want to do some math
local Pos1 = Vector3.new(10,10,5)
local Pos2 = Vector3.new(5,7,9)
local Sum = Pos1 + Pos2 -- Vectors can be added together
local Diff = Pos1 - Pos2 -- Vectors can be subtracted from each other
local X = Pos1.X -- every Vector have X,Y,Z property that can be read-only, this mean you can't change it manually
local Y = Pos1.Y
local Z = Pos1.Z
If you don’t know, Vector math works this way:
Vector1 - Vector2 = (Vector1.X - Vector2.X, Vector1.Y - Vector2.Y, Vector1.Z - Vector2.Z)
I also mentioned that Vectors in math have direction and value, they also can be defined
local direction = (Vector1 - Vector2).Unit -- vector with lenght of 1 and direction
local distance = (Vector1 - Vector2).Magnitude -- lenght of vector
IMPORTANT NOTE: If you will use raycasting or anything that works similar in the future, in place of Ray’s direction simply put: (Origin - Hit)
because you need both distance and direction, for those who don’t know, Origin is start, and Hit is position where we want to finish our ray
Note: If you want to know Vectors you should know math, those are 4 long courses that could help you a lot:
Vectors and Dot product: https://www.youtube.com/watch?v=MOYiVLEnhrw
Cross product and Spaces: https://www.youtube.com/watch?v=XiwEyopOMqg&list=PL03cIZW_q0Hd7asKLLS0kZnr_R6P-wkVx&index=2
Trigonometry: https://www.youtube.com/watch?v=1NLekEd770w&list=PL03cIZW_q0Hd7asKLLS0kZnr_R6P-wkVx&index=3
I reccomend watching them, thanks to them i understood Vectors on advanced level, if you simply want to become master of them, watch 3 of them
Thanks for reading, have a nice day, Godbye!
4. Events
Welcome, today we will talk about Events
Events are something important that will happen in exact date, Events are usually big and made as best as possible they can be, Events usually have some consequences or aftermatch that is seen long after it’s end
In Programming Events are listeners that will start your code when something happen, for example if player typed: “Hello” in chat then he will turn into rocket and go to the moon, or maybe player touched the lava and start glowing like it
Those are typical examples of Event&Script that works together
But how to use them???
local Part = Instance.new("Part")
Part.Name = "Lava"
Part.Anchored = true
Part.CanCollide = false
Part.CastShadow = false
Part.Material = Enum.Material.Neon -- Materials are Enums like shapes
Part.Color = Color3.new(255,0,50)
Part.Size = Vector3.new(40,1,40) -- Size is vector because it's in 3D space
Part.Position = Vector3.new(0,10,0) -- Position is vector because it's in 3D space
Part.Parent = workspace
local function OnTouched(Hit: Basepart)
end
Part.Touched:Connect(OnTouched)
what is this connection of function and some new stuff????
As you can see, we created new Part named Lava, and we created local function called OnTouched, it’s clear that this Function should run when Part is touched, we know this by name, but how to fire this function in the first place??? we can use our standart:
OnTouched(???)
Why is there ??? instead of Basepart?
Because we don’t have this Basepart, and also if we will call this like a normal Function it will run when game will start and this is it!
But when we connected Event to this function, every time it will be fired by some change in game or Player’s action, then it will run connected Function too!
How we can know where are events? it’s simple, all of possible events are described in docs:
Roblox Engine Classes | Documentation - Roblox Creator Hub
There are every class and their methoods, events and other stuff
But now, when we know what Events are, where we can use it?
local function OnTouched(Hit:Basepart)
end
Part.Touched:Connect(OnTouched)
Why is there Hit in function's arguments???
Some Events have their own arguments that they can share with Functions, in this situation when Touched Event is fired, then it returns us another Basepart that touched our Lava
What else we can do with Events???
Part.Touched:Connect(function(Hit) -- this way we can create Event faster, also there is no need for type, it's set already
-- code
end) -- remember to add ) to end, it's specifci when we create quick Event
Above we can see quick Event as i like to call it, it's the same as the normal way to connect it, you can use methood that you like or both, depending on your coding style
local connection
connection = Part.Touched:Connect(OnTouched) -- we define our RBX connection by this variable
task.wait(5)
connection:Disconnect() -- disconnects the event, very usefull for optimization
As you can see above, after 5 seconds Event will not longer work, because connection is disconnected, you can use prints inside event to test it out
There is more stuff we can do with Events
Part.Touched:Once(OnTouched) -- Event will fire only once and then it will disconnect
Above we have very usefull thing, sadly it’s not used that often, it’s very usefull for game’s Glory Moment that appears only once and for all
For instance nuke launch button, it will be pressed only Once and then no one will use it again, in this case we can simply listen to Event once and then remove detector
-- code
local Hit = Part.Touched:Wait()
-- code
Also we can Wait, this will wait until Event will be fired, and then it will return the argument of this Event
Part.Touched:ConnectParrarel(OnTouched)
This above connects Event with multi-threading and parrarel Lua, it’s more advanced topic soo i’ll leave link to it:
Parallel Luau | Documentation - Roblox Creator Hub
Thanks for today, have a nice day, Godbye!
5. Detectors
Welcome, today we will learn about Detectors
What are they?
Detectors are special type of object, that usually allows us to fire Events when player clicks, presses key or drags something
There are 3 main Detectors, i’ll talk only about 2 because third is less used and it’s kind-of new
Types:
- Click detector
- Proximity Prompt
- Drag Detector
Of course all 3 of them are instances that go under part that should be interacted with
local Part = workspace.Part
Part.ClickDetector.MouseClick:Connect(function(plr:Player)
-- after clicking on part with left mouse button, some action performs
end)
As you can see we simply detected player clicking on server which is nice, also we can use other methoods (they will highlight, you can also detect mouse hovering over Detector’s Parent or right click) to perform different actions
IMPORTANT NOTE: Some detectors will have property called: Adorne, you have to press it and then select Basepart in Explorer soo it can appear over it, remember to turn off Required sine of view when you can’t see it, usually invisible part blocks it
local Part = workspace.Part
local Prompt = Part.Prompt
Prompt.Triggered:Connect(function(plr:Player)
Part.Transparency += 0.01 -- after 100 times part would be invisible!
end)
[spoiler]`` Above we have function that makes after triggering prompt Part will become slighty
Prompts have also Events to detect if someone started to hold them or if you finished it, you can read about what specific Events does by code hits, when you put dot before Event you can have highlighted every single methood that can be used on this Object, it also works with colon when you call methoods
Why you don't talked about this third???
Because drag detector aren’t detector only!, it’s object that allows you to drag part like a wood from lumber tycon!
It also uses Filtering with it’s RunLocally property, we didn’t talked about this concept, which is very complex and crucial!
Drag detectors are great addition, before we required crazy math and replication with a lot of checks to do that, but i only mentioned them to let people know about this thing.
At the end, Roblox’s built-in Detectors are great way to detect player inputs without replication, you can use them to create interactive elements of your game easily
Drag detectors for those who are intrested: Drag Detectors | Documentation - Roblox Creator Hub
Thanks for today, have a nice day, Godbye!
6.CFrames
This text will be hidden
7.Attributes
This text will be hidden
8.Linear Interpolation
This text will be hidden
9.Services
This text will be hidden
10.Enums
This text will be hidden