Scripting Manual Part 2

Our previous tutorial: Scripting Manual

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 :hearts:

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

Welcome, today we will learn about CFrames

See, this topic is extension of Vectors, soo be sure to read it before

Before we will ask what CFrame is we have to ask what Matrice is

In math, Matrice is like 2D table that contains values

Right Up Forward Position
Rx Ux Fx X
Ry Uy Fy Y
Rz Uz Fz Z
0 0 0 1

This is CFrame visualized as Matrix

You know that position is a Vector, Right, Up, Forward are also Vectors, but they represent direction where object looks at depending on Face, you can get them by calling:

local LookVector = Part.CFrame.LookVector
local RightVector = Part.CFrame.RightVector
local UpVector = Part.CFrame.UpVector

-- you can multiply those vectors to get lenght and direction of raycasts

Why we would need them???

See in vector math, they are pretty common, raycasts are mostly used hitbox detection methood, and most of the time when you’ll create guns and cannons or anything like that you would get direction and force of projectiles by multiplying those directional Vectors and using them with math to achieve the best results

But for now they were very important for us, because you might think

What is the difference between CFrames and Vectors???

CFrame is Matrix that holds 3D Position and Rotation using directions, it can be converted to World and Object space and also manipulated by math

Why would we need that??? again...

Many objects in Roblox uses CFrames, rotating player’s head to mouse position or changing motor6D is also CFrame work

local NewCFrame = CFrame.new(5,4,3) -- creates new CFrame with Position(0,0,0) but with default rotation of (0,0,0)

Part.CFrame = NewCFrame -- as you can see, part moved to this position

-- but also rotation changed!

As you can see, CFrame when used changes also rotation, it can be annoying but also very powerfull

Now if you know how CFrames work, we can do some math!

local CFrame1 = CFrame.new(3,4,5)
local CFrame2 = CFrame.new(2,1,0)

local Part = workspace.Part

Part.CFrame = CFrame1 * CFrame2 -- multiplying cframes

IMPORTANT NOTE: Dividing CFrames are different than multiplying, multiplying is like addition, but to subtract them you need to use other methood!!!

local CFrame1 = CFrame.new(3,4,5)
local CFrame2 = CFrame.new(0,2,2)

local Part = workspace.Part

Part.CFrame = CFrame1 * CFrame2 -- Part's CFrame Position is now (3,6,7)

Part.CFrame = CFrame1 * CFrame2:Inverse() -- Part's CFrame Position is now (3,2,3)

Inverse() methood allows us to inverse CFrame soo it will be like negative one

There are plenty of other strange methoods, but now we will show you second most important one

local CFrame = CFrame.new(4,5,7) * CFrame.Angles(math.pi/5,math.pi/8,math.pi/3)

local Part = workspace.Part
local x,y,z = CFrame:ToOrientation() -- converts CFrame to x,y,z of orientation

Part.Orientation = Vector3.new(x,y,z) 

Don’t worry about this CFrame.Angles, we will talk about it in a moment

I told you that CFrames are also rotation, we can set it by few ways, one is more mathematical and uses Matrices to do that, other is simply Roblox’s function, CFrame.Angles

local CFrame1 = CFrame.new(3,4,5) * CFrame.Angles(math.pi/4,math.pi/2,math.pi/8)

-- remember that rotation is in Radians, there is a math.rad function that converts degree to Radians
-- additionaly you can use math.pi divided by some number (math.pi returns 180 degree in Radians)
-- other than that, there is math formula for that: degree / (180 / math.pi)

Part.CFrame = CFrame1

IMPORTANT NOTE: There is tutorial made by @Kriko_YT that covers how to replace Roblox’s functions with far more efficient CFrame math, here is link: Understanding CFrame with Matrices!


Now let’s talk about some new concept, Object and World space, they are very simple although many don’t understand them properly

Imagine that you standing in front of the building, you see that this building is in front of you, but let’s say there is a person who was in the building and now he left it, the building is in this person’s back

Object space is space dependant on perspective!!! This mean every part have their own perspective, directional vectors are great example, one's part front is other's back or right

On the other hand, World space is space shared by **everyone**. No matter what will happen, the world space is one, everyone shares it, Part can have negative coordinates but also positive, but when part will rotate nothing will change

When we know what is the difference between two spaces, we can now try to find use for them

See, plot building is the best example, when we want to save building and different plots have different rotation, we can get plot’s CFrame and player’s build

local plotCFrame = plot.CFrame
local buildCFrame = build.CFrame

local SaveCFrame = plotCFrame:ToObjectSpace(buildCFrame) * CFrame.new(0,plot.Size.Y,0)

-- Remember, calling plotCFrame:ToObjectSpace(buildCFrame) will convert buildCFrame to plotCFrame's object space

How to load this when it's saved?

build.CFrame = plot.CFrame * SaveCFrame -- build will be placed the same independently of it's rotation

There are many more to learn, World Space is used occasionally with more specific systems, you’ll probably use it with advanced math

CFrames are much more advanced than what i said today, but for you it’s enough to use them for most of the time

Thanks for reading, have a nice day, Godbye!

7. Attributes

Welcome, today we will learn about Attributes

this tutorial is very quick, almost no coding, first let’s talk about Attributes

Attribute is some data inside Instances, there are few types like Color, Vector, number, boolean, string, object and few others

They are usefull for storing data like tool’s propertiess or settings without need of creating additional 10 Instances

local att = Instance:GetAttribute("attribute's name") -- return specific attribute's value

local all = Instance:GetAttributes() -- returns table of every attribute as key and their values

Instance:SetAttribute("New number",5) -- sets new attribute to Instance

This is it, only 3 methoods???

Yea, only, Attributes are very efficient and usefull element of Roblox, and very simple to use, you can also add them manually by sliding down in Propertiess and then pressing
Create new attribute button

Thanks for today, have a nice day, Godbye!

8. Linear Interpolation

Welcome today we will learn about Linear Interpolation, also known as LERP

You might heard about Tween Service, it uses the same idea but in more Roblox way

If you never heard about it, then don’t worry, i’ll explain what are LERPS in a moment

Soo what are they???

LERP is pretty much mathematical formula to calculate number between two other numbers

LERP = a + (b - a) * t

Explanation:

a - starting number or position
b - number or position that we finish on
t - percent (0-1) at which point we want to calculate it

Ok???

Don’t worry, for simplier explanation, we have smaller number and larger number, and we want to calculate what number is in half way from lower to highest number, we can use then this formula and replace a with smaller number, b with higher and of course t with 0.5 because 0.5 is 50% which is half way

local start = Vector3.new(0,10,0)
local finish = Vector3.new(40,10,0)

local part = workspace.Part
---------------------------------------------------------
local function LERP(a,b,t)
   return a  + (b - a) * t
end

task.wait(3)

for i = 0,1,0.01 do
   part.Position = LERP(start,finish,i) -- will lerp 100 times
   task.wait() -- remember to add this, soo it would be smoth rather than instant transition
end

As you can see, our Part will move smoothly from (0,10,0) to (40,10,0)

NOTE: if you want to know how to lerp with easing styles and overall why lerping is better than tweening, you can read this article: https://devforum.roblox.com/t/simple-alternative-for-optimization-instead-of-using-tweenservice-explaining-interpolation

IMPORTANT NOTE: LERPS should be mainly used on client! they are better than Tween Service but still performant heavy!!! Use them wisely and you’ll be ok

And this was everything today, i believe you now learned that LERP is very usefull for smooth transition, and you can make beatifull VFX with it, have a nice day, Godbye!

9. Services

Welcome today we will talk about what Services are and how to use them, let’s start

Services are Roblox’s Api most noticable addition, they have different functions, you can use them like tools, they also have their own Events or methoods

local TweenService = game:GetService("TweenService") -- we call service by it's name, they'll highlight

I told about Tween Service in previous tutorial, it’s one of many Services in Roblox and it’s commonly used by those who don’t use LERP or likes to play with effects

local Debris = game:GetService("Debris")

Another type of Service is Debris, it simply can add something to be destroyed after X seconds, usually used for VFX too

local toRemove = workspace.PartToRemove
Debris:AddItem(toRemove,5)

Part would be removed after 5 seconds

As you can see above, Debris have it’s own methood called: AddItem(Instance,Time) that destroys thing like :Destroy() but after X time

local RunService = game:GetService("RunService") -- Runs game and simulations

RunService.HeartBeat:Connect(function(deltaTime)
-- do something
end)

Will run code every simulation frame completion

Above there is example of Event of Run Service connected to some function

Services are tools that you’ll use for specific stuff, maybe player pressing keys or advanced effects, maybe it will be tagging objects to optimize game, or doing mobile compatibility, it depends on what you are working on

local ReplicatedStorage = game:GetService("ReplicatedStorage") -- it's better to use it, for both visual and some other technical stuff to prevent bugs

NOTE: it’s good to call normal services by :GetService(Service Name) than by dot, it’s better for visual and also prevents some technical bugs and don’t break the game

Thanks for today, have a nice day, Godbye!

10. Enums

Welcome, today we will learn about Enums

I talked about them, there are pretty much nothing to talk about, but you have to know what are they

local Part = workspace.Part
Part.Material = Enum.Material.Neon

Material of part will change to neon

Pretty much only i can say about Enums is that they are Roblox’s data values, they store different propertiess and they are used for some stuff, but not everything, here are few examples:

  • Material changing
  • Shape changing
  • Keybind describtion

Enums also have one methood

local EnumItems = Enum.Material.Neon:GetEnumItems()

print(EnumItems) -- prints table of: Neon, some value, Material

-- alternative

local EnumValue = Enum.Material.Neon.Value
local EnumName = Enum.Material.Neon.Name
locsal EnumType = Enum.Material.Neon.EnumType

Those parts of Enum are it’s elements, you can read about them here:
Enums | Documentation - Roblox Creator Hub

You can pretty much use them in different scenarios, it’s important to know what they are, and you’ll be fine

Thanks for today, we ended our first half of intermediate programming, next topics would be very hard soo prepare and practice those that we learned to this point, have a nice day, Godbye!

11. Filtering

This text will be hidden

12. Local scripts

This text will be hidden

13. Basic GUI programming

This text will be hidden

14. Tween Service

This text will be hidden

15. Client & Server rules

This text will be hidden

3 Likes