织梦CMS - 轻松建站从此开始!

欧博ABG-会员注册-官网网址

欧博[Full Tutorial] How to script on Roblox

时间:2025-10-07 11:20来源: 作者:admin 点击: 12 次
How do script [ Update Version], 2022/2023 Introduction Hey there! Today, I will be teaching you how to script from scratch - all the basics you need

Part 2 Remote Events & Functions

In this section, we’ll be talking about Remote Events & Remote Functions + how to secure them as much as possible.

Introduction:

So first, what are they and why do we need them?
To those of you who didn’t know, back then - before Roblox changed and updated their filterenabled system & security, exploiters could basically do any type of exploit they wanted - it was a disaster, tons of exploits that ruined some good & popular games. And that’s when Roblox have decied to add remote event and functions. This wouldn’t completely stop exploiters tho, but it SIGNIFICANTALLY changed and fixed tons of issues, including patching alot of exploits that no longer work.

Idea:

As mentioned above, the idea of using RemoteEvents and RemoteFunctions is to help us handle our game as correctly as possible, and to protect our game from being completely ruined. From the moment they were added, we now can use them to prevent exploiters from doing some crazy and weird exploits. Le’ts begin!

Remote Events

A remote event allows us to : one-way communicate across the client-server boundary. You can use it to send requests across the boundary without yielding for a response.[ Meaning: You could use these to handle things on the server / client when needed.

When can I use remote events ?
Remote events are good to use in these cases:

Client --> Server

Using this to fire an event from a certain client[player] to the server, so that everyone could see those changes. Let’s have an example:

--Local Script, StarterGui local Replicated = game:GetService("ReplicatedStorage") local UserInput = game:GetService("UserInputService") local Remote = Replicated:WaitForChild("ClientServer") UserInput.InputBegan:Connect(function(Key,IsTyping) if IsTyping then return end -- if he's typing in chat/anything like that. if Key.KeyCode == Enum.KeyCode.K then Remote:FireServer("string1",Color3.fromHSV(0.056, 0.501961, 1),25) end end) --Server Script local Replicated = game:GetService("ReplicatedStorage") local Remote = Replicated.ClientServer Remote.OnServerEvent:Connect(function(Player,arg1,arg2,arg3) -- Player is the player who fired the remote. --Let's check their types, to see that an exploiter didn't provide a not matching type --If the types are not matching, we end the function. if typeof(arg1) ~= "string" and typeof(arg2) ~= "Color3" and typeof(arg3) ~= "number" then return end print(Player.Name.." has fired a remote!") end) Server --> Client --Server Script local Replicated = game:GetService("ReplicatedStorage") local Players = game:GetService("Players") local Remote = Replicated.ServerClient Players.PlayerAdded:Connect(function(Player) Remote:FireClient(Player,Player.Name) end) --Local Script, StarterPlayerScripts local Replicated = game:GetService("ReplicatedStorage") local Remote = Replicated:WaitForChild("ServerClient") Remote.OnClientEvent:Connect(function(Player) game:GetService("StarterGui"):SetCore("ChatMakeSystemMessage",{ Text = string.format("Hey %s , welcome to the game!",Player); Color = Color3.fromRGB(85, 255, 127) }) end) Server --> All Clients --Server Script local Replicated = game:GetService("ReplicatedStorage") local Players = game:GetService("Players") local Remote = Replicated.ServerClients Players.PlayerAdded:Connect(function(Player) Remote:FireAllClients(Player.Name) end) --Local Script, StarterPlayerScripts local Replicated = game:GetService("ReplicatedStorage") local Remote = Replicated:WaitForChild("ServerClients") Remote.OnClientEvent:Connect(function(Player) game:GetService("StarterGui"):SetCore("ChatMakeSystemMessage",{ Text = string.format("%s has joined the game!",Player); Color = Color3.fromRGB(255, 170, 127) }) end)

As you can see here, on the server side, we’re using FireAllClients() function, which would fire/ notify every client[player] in the game, about the given event/message provided / made on the client. Note: the message could’ve been made on the server and sent as the second argument within the FireAllClients().
On the client side, we use game:GetService("StarterGui"):SetCore() to create a message on chat, so that everyone in-game can see that.

Client --> Other Client

This can’t be directly done, so it has to be through the server. Here is how:
You can use FireServer() to share the server with the changes, then on the server, use FireClient() or FireAllClients() to fire the client[s] ,and then use OnClientEvent() on the client to do the stuff.

Remote Functions

A remote function , unlike remote events, allow us to two-way communicate across the client-server boundary. You can use it to send requests across the boundary and yield for a response. Here it what it means:

Player1: Invokes the server [ using InvokeServer()], then, on the server ,he returns something [ most commonly is booleans], and then - on the client, he can use that result after he assigned the InvokeServer() call as a variable, like this -local call = remote:InvokeServer(). (This is very useful when we want to make a code redeeming system, for example, or even a trade system).

When can I use remote functions?
Remote functions are good to use in these cases:

Client -- > Server --LocalScript, under a `ScreenGui`. local Replicated = game:GetService("ReplicatedStorage") local Remote = Replicated:WaitForChild("ClientServer") local Button = script.Parent.Release local Input = script.Parent.Input local ResultText = script.Parent.Result Button.MouseButton1Click:Connect(function() local Result = Remote:InvokeServer(Input.Text) if Result then -- if the code was valid ResultText.Text = "SUCCESS" else -- if the code wasnt valid ResultText.Text = "FALED" end task.wait(3) ResultText.Text = "" -- 'making the text invisible - no text' end) --Server Script local Replicated = game:GetService("ReplicatedStorage") local Remote = Replicated:WaitForChild("ClientServer") local Codes = { ["Test1"] = 250, ["FREE"] = 50 } Remote.OnServerInvoke = function(Player,Code) if typeof(Code) ~= "string" then return end print(string.format("%s has redeemed the input: %s",Player.Name,Code)) if not Codes[Code] then return false else return true end end Server --> Client

Not recommended, do not try it unless you’ve a strong sanity checks that would prevent exploiters from ruining and messing up with it. These are the risks you could have with it:

1.If the client throws an error, the server throws the error too.
2.If the client disconnects while it’s being invoked, then throws an error.
3.If the client doesn’t return a value, the server yields forever.

Player & Character

In this section, we’ll be talking about the Player and its ‘visual’ appearance - the Character.
We’ll talk about how they’re different, and what each has and offers, that the second - does not.

Player

The Player is an object/instance, where you can view most of the main things/properties your player/other players have in-game[ and some can actually give info from out of the game]. To be a bit more accurate, every Player object represents the Client when they’re connected to the game.

Properties

Like every other object, the Player object has properties aswell, let’s review some of them:

Character

This property is an ObjectValue, and it should represent the actual model of the player - the character [ which we can visually see in-games].

DisplayName

Obviously, this property is a String, and it should represent the DisplayName of the player.

AccountAge [Read Only]

This property is a Number , and it automatically updates the Age [in days] of the player.
NOTICE: this property is read only, meaning - you can’t modify or change that property.

Team

This property belongs to the Team class, and this allows us to know/edit and change the player’s team.The Team value itself, is an ObjectValue. And it’s supposed to represent the player’s team or nil [if the team doesnt exist/destroyed].

Events

In here, we’ll be talking about some cool and useful events the Player object has.

CharacterAdded(Character)

This event should fire every time the player’s character spawns or respawns.

local Players = game:GetService("Players") Players.PlayerAdded:Connect(function(Player) print(Player.Name.."- Player Instance") Player.CharacterAdded:Connect(function(Character) print(Character.Name.."- Model Instance") end) end) Chatted(Message)

This event would fire each time the player is chatting through Roblox built-in chat.

local Players = game:GetService("Players") Players.PlayerAdded:Connect(function(Player) Player.Chatted:Connect(function(Message) print(string.format("%s has said the word: %s",Player.Name,Message)) end) end) Methods

In here, we’ll be talking about some useful methods you might need to know and use.

ClearCharacterAppearance()

This method would remove all accessories and objects from the player’s character.[if they are decals, accessories and clothes].

local Players = game:GetService("Players") Players.PlayerAdded:Connect(function(Player) print(Player.Name.."- Player Instance") Player.CharacterAppearanceLoaded:Connect(function(Character) Player:ClearCharacterAppearance() end) end) Kick(Message)

This method would kick the player from your game and show him the given message [if given], if not,t then the default Roblox message.

local Players = game:GetService("Players") Players.PlayerAdded:Connect(function(Player) Player:Kick("Test") end) Character

The Character is a Model object, which should represent the player’s character [ or any player’s character], and can also be used for making NPC’s. Every character essentially contains:
Humanoid ,HumanoidRootPart and a Head part. About other limbs - depending on what rig you’re using [R6 or R15].The character is the entity of yourself and other players in games , which allows you to do actions [ run, walk,sit, jump ,dance] and more things that can be viewed from the character prespective.

Properties

Like every other object/instance, the Character object has properties aswell, let’s review some of them.

Archivable

This property [ boolean ] would determine if the object is included in the game and can be seen when published and it also impacts to clone objects. If set to false, the object won’t be cloned. If set to true, the object will be cloned when using the Clone() method.

local newObject = Instance.new("Part") print(newObject:Clone()) --> Part, because `Archivable` is automatically set here to true newObject.Archivable = false print(newObject:Clone()) --> nil PrimaryPart

This is an ObjectValue, which refers to the PrimaryPart of your model. You should know that -
The primary part acts like the physical reference for the pivot of the model, which basically means -
The pivot will move in sync with the primary part. If the primary part is not set, the pivot will stay at the same position in world space even if parts within the model are no longer there.
It is also important to mention that when setting a primary part, that primary part has to be a descendant of that model, or else - setting that primary part will change it to nil automatically.

Events

In here, we’ll be talking about some useful events to use on our character.

AncestryChanged()

This event would run when the parent or any of its ancestors is changed. It includes 2 parameters: child and parent. Where:

child is the object whose parent was changed.
parent is the new parent of that child[object].

local Baseplate = game.Workspace.Baseplate Baseplate.AncestryChanged:Connect(function(Child,Parent) print(Child.Name .. " is now a child of " .. Parent.Name) end) Baseplate.Parent = workspace.isModel Methods

In this section, we’ll be learning about some cool and useful methods to use on our character.

BreakJoints()

This method will break any connection between parts in your character. Using this on your character, will kill you [ by killing your humanoid].

local Players = game:GetService("Players") Players.PlayerAdded:Connect(function(Player) Player.CharacterAdded:Connect(function(Char) task.wait(1) Char:BreakJoints() end) end) MoveTo()

This method will move the character/any model’s primary part to the provided position.Make sure your model always has a PrimaryPart. Because if your model doesnt have one, this would select the root part of that model as the primary part. And, since the root part is not deterministic, it is recommended to always set a primary part.

Tools, Backpack & StarterGear

In this section, we’ll be talking about tools, backpack ,startergear, and how to use and how they work.

Tools

By definition, tools on Roblox are objects which the Character[ if he has a humanoid within], can equip , unequip and activate it. Notice this pattern:
Tool is in Backpack → Player Equips it – > Tools is now in his Character.
When you place tools in StarterPack, this would put all the given tools under the player’s Backpack folder. [From where he can equip his tools].

You notice that when you die, you lose your tools. How can you prevent this?
Simply make sure the tools are also in StarterGear, this would give you those items each time you die/reset.

On desktops,pressing a number key (1, 2, 3…) will equip the tool whose index is at that number key.
[Meaning, pressing 1 should give you the first tool, etc.]
Let’s review a quick example:

local tool = script.Parent local function explode(point) local e = Instance.new("Explosion") e.DestroyJointRadiusPercent = 0 e.Position = point e.Parent = workspace end local function Activated() --Getting the humanoid of the tool's owner local human = tool.Parent.Humanoid --Calling the explode function explode(human.TargetPoint) end --Connecting the Activated event to the Activated function tool.Activated:Connect(Activated)

The tool in the above example will create an explosion at the position of the tool owner.
Let’s now move onto Properties, Events and Methods.

Properties

In here, we’ll be talking about some useful properties you might need when working with tools.

CanBeDropped [ boolean ]

This property will determine if you can drop your tool [by pressing Backspace] or not.

Enabled [ boolean ]

This property will determine if you can actually use the tool or not.[ Say you wanted to remain that tool in the player’s backpack, but only preventing him from using it].
When set to true, the player can use the tool. When set to false, the tool is disabled and the player cannot use it. This would also prevent any Activation / Deactivation events from happening, since you aren’t able to use the tool if set to false.

RequiresHandle [ boolean ]

This property determines if your tool can work without the need of a handle.
[Meaning that if your tool doesnt have a handle, and that property is set to false, then you could still activate your tool and do stuff].

Events

In here, we’ll be talking about some useful events on tools.

Activated

This event runs whenever the player clicks while equipping a tool.
[Do not get confused with the method Activate().]

local Tool = script.Parent Tool.Activated:Connect(function() print(string.format("%s was activated!",Tool.Name)) end) Equipped

This event runs whenever the player equips a tool.

local Tool = script.Parent Tool.Equipped:Connect(function() print(string.format("%s was equipped!",Tool.Name)) end) Methods

In this section, we’ll be learning about some useful methods to do with tools.

ClearAllChildren()

This method simply clears every child / descendant of the given object.
Notice that if you’re wishing to not clear completely all children, you could use a for loop + an if statement to check the class of the children , etc.

Gamepasses & DevProducts

In this category, we’ll be trying to understand the ideas behind gamepasses and devproducts, and what they do.Before we dive into that, let’s first explain what service they stand behind.
As you might know, each service in Roblox Studio has different types of tasks to do/get.
And obviously, not all services are shown in the Explorer.

In this part, we’ll be using the Marketplace Service.
MarketplaceService allows us to configure and work with in-game transactions, use its methods to fetch information about developer products and gamepasses, and more assets.

It has many many events, as well as methods. We’ll be talking about some prominent ones.

Events

Here,we’ll be talking about some very useful events to work with MarketplaceService.

PromptGamePassPurchaseFinished

This event would run whenever the purchase dialog of a game pass is closed.Meaning whenever the player presses either ‘OK’ or ‘Cancel’.

It contains 3 parameters:

player[instance]: the player object whom got the prompt.
gamePassId[number]: the id of our gamepass.
wasPurchased[boolean]: checks if it was purchased or not.

--Defining Services local MarketplaceService = game:GetService("MarketplaceService") local Players = game:GetService("Players") --Making a Function local function gamepassPurchaseFinished(player,id,purchased) print(player,id,purchased) print("PromptGamePassPurchaseFinished", player,id,purchased) end MarketplaceService.PromptGamePassPurchaseFinished:Connect(gamepassPurchaseFinished) task.wait(5) --Prompting a Gamepass Purchase for the testing MarketplaceService:PromptGamePassPurchase(Players.LocalPlayer,87186006) --In this case, we got: --[[ PromptGamePassPurchaseFinished Valkyrop 87186006 false ]]

Notice that we got false here, because I already own this gamepass.

PromptPremiumPurchaseFinished

Fires whenever the premium purchase modal closes[ meaning ‘Cancel’ or ‘OK’ buttons].

--Defining Services local MarketplaceService = game:GetService("MarketplaceService") local Players = game:GetService("Players") MarketplaceService.PromptPremiumPurchaseFinished:Connect(function() print("Player either closed or purchased premium!") end) task.wait(5) --Prompting a Gamepass Purchase for the testing MarketplaceService:PromptPremiumPurchase(Players.LocalPlayer) Methods

In this section, we’ll be learning about some useful methods.

PromptGamePassPurchase()

This method prompts the given player, the given gamePassID.

--Defining Services local MarketplaceService = game:GetService("MarketplaceService") local Players = game:GetService("Players") local GamepassID = 000000000 -- change it to your gamepass ID --Prompting a Gamepass Purchase for the testing MarketplaceService:PromptGamePassPurchase(Players.LocalPlayer,GamepassID) PromptPremiumPurchase()

This method simply prompts the player to buy/get premium from the game.[Only parameter is the player whom this will be shown to].

GetDeveloperProductsAsync()

This method returns pages/lists of all current DevProducts the game has.

local MarketplaceService = game:GetService("MarketplaceService") local developerProducts = MarketplaceService:GetDeveloperProductsAsync():GetCurrentPage() for _, devProduct in pairs(developerProducts) do for index, value in pairs(devProduct) do print(index .. ": " .. value) end print(" ") end --Result: --[[ DeveloperProductId: 16344291 displayName: Developer Product 1 Name: Developer Product 1 ProductId: 1316305655 PriceInRobux: 25 ]] GetProductInfo()

This method returns information about an asset,dev product or even a gamepass.
You should provide the assetID + assetType, meaning:

local success,result = pcall(function() return MarketService:GetProductInfo(87186006,Enum.InfoType.GamePass) end) ClickDetectors & ProximityPrompts

In this section, we’ll be learning about ClickDetectors and ProximityPrompts.

Introduction:

So, before we dive into it. Let’s first understand what they are and what they do.

ClickDetectors:allow us receive pointer input on 3D objects through their MouseClick event, meaning - lets us click on objects with our cursor, and do lots of stuff. They only work if they’re parented to:
BasePart, Model or Folder's. Here is a very simple example:

--Assuming you have this script under a clickdetector which is under a part. script.Parent.MouseClick:Connect(function() print("Someone has clicked on me!") end)

ProximityPrompts: unlike ClickDetectors, ProximityPrompts are visualized gui that appears each time the player approaches to objects, within a certain range of a distance.
Here is a simple example:

--Assuming you have this script under a ProximityPrompt which is under a Part script.Parent.Triggered:Connect(function() print("Someone has pressed this Prompt!") end) ClickDetectors

So after that introduction, let’s begin by learning some of its properties and events.

Properties CursorIcon[Content]

This property allows you to change the icon of your cursor.

MaxActivationDistance[number]

This property tells you from what distance you’re able to click and activate that clickdetector.

Events MouseClick

This event fires everytime a player presses and releases the left mouse button while the cursor is hovering over a model or any basepart with a clickdetector.Also, it’s important for the player’s character to be within the MaxActivationDistance, in order to activate it.

local clickDetector = script.Parent:FindFirstChild("ClickDetector") clickDetector.MouseClick:Connect(function(Player) -- Player is a parameter for the player who clicked on it print(string.format("%s has pressed on me!",Player.Name)) end) MouseHoverEnter

This event runs whenever the player begins to hover his cursor over the ClickDetector's parent.[Can be used in both Script and LocalScript].

local clickDetector = script.Parent:FindFirstChild("ClickDetector") clickDetector.MouseHoverEnter:Connect(function(Player) -- Player is a parameter for the player who clicked on it print(string.format("%s has hovered his cursor!",Player.Name)) end) ProximityPrompts

So after that introduction, let’s begin by learning some of its properties and events.

Properties ActionText[string]

This property is where the text you’ll see on your prompt, like this:

image

HoldDuration[float]

This would determine how long the player would have to hold the prompt.

MaxActivationDistance[float]

This would help you determine from what distance the player can activate the prompt.

Events Triggered

This event runs whenever the player has done clicking/holding the prompt [and finished it].

script.Parent.Triggered:Connect(function() print("Prompt has been triggered!") game.Workspace.Baseplate.Size = Vector3.new(4,4,4) end) PromptButtonHoldBegan

This event runs whenever the prompt is being held by the player[make sure HoldDuration is > 0].

script.Parent.PromptButtonHoldBegan:Connect(function() print("Prompt triggering has begun") end)

TweenService

In this section, we’ll be learning about TweenService, what it does and how to use it.

Introduction:

Tweens are used to interpolate the properties of instances. Meaning, to edit,modify and change them in style/animation.Notice! Only the following types can be used in TweenService:

image

.

To start using this server and its features, you should use the main function : TweenService:Create(), which takes information about the object and acts accordingly when playing the tween.

NOTES:
1.You can tween multiple properties at the same time.
2.If you’re trying to tween the same properties at the same time, only the last one of those properties would tween.

Examples 1.Tweening part size local tweenService = game:GetService("TweenService") local Part= script.Parent local tweenInfo = TweenInfo.new( 2, -- Time Enum.EasingStyle.Linear, --Style Enum.EasingDirection.Out, -- Direction -1, --RepeatCount.[if it's <0 this would loop forever] true, -- Reverse 0 -- daly ) local Goal = { -- properties to change Size = Vector3.new(10,10,10) } local PartTween = tweenService:Create(Part,tweenInfo,Goal) -- preparing the animation PartTween:Play() -- playing the tween task.wait(7) -- delay PartTween:Cancel() -- this will stop the tweening 2. Tweening part size and Color local tweenService = game:GetService("TweenService") local Part= script.Parent local tweenInfo = TweenInfo.new( 2, -- Time Enum.EasingStyle.Linear, --Style Enum.EasingDirection.Out, -- Direction -1, --RepeatCount.[if it's <0 this would loop forever] true, -- Reverse 0 -- daly ) local Goal = { Size = Vector3.new(10,10,10), Color = Color3.fromRGB(0, 85, 255) } local PartTween = tweenService:Create(Part,tweenInfo,Goal) PartTween:Play() task.wait(7) PartTween:Cancel() --Change the part color to 'Really Red' to see the efffect. Tweening a Door Spin local tweenService = game:GetService("TweenService") local Door= script.Parent local tweenInfo = TweenInfo.new( 2, -- Time Enum.EasingStyle.Linear, --Style Enum.EasingDirection.Out, -- Direction -1, --RepeatCount.[if it's <0 this would loop forever] false, -- Reverse 0 -- daly ) local Goal = { CFrame = Door.CFrame * CFrame.Angles(0,math.rad(180),0), } local Tween = tweenService:Create(Door,tweenInfo,Goal) Tween:Play() Camera

In this section, we’ll be learning about Camera ; what it is , and what it does.

Introduction:

Camera on Roblox is a special object which lets us define and view the world from a 3D prespective.
Every time a client[player] joins the game, he has his own camera object.
We can’t access others camera through the server,only on the client, and access ours only. To access/find the camera object, we use Workspace.CurrentCamera.

The Camera object has many important proprties, however - only 5 of them are more important than others, and these are:

[Camera.CFrame]: Simply represents the position and rotation of the camera.
[Camera.Focus](CFrame): Simply sets the focus of the camera to the given CFrame, it is the point where the camera is looking.
[Camera.CameraType]: Determines how will the camera update every frame.
[Camera.CameraSubject]: Determines what object should the camera follow.
[Camera.FieldOfView]: Determines the observable world through the camera field of view.
The bigger the number, the further the field of view is.

Examples: Switching Camera Objects --Variables local camera = workspace.CurrentCamera local players = game:GetService("Players") local player = players.LocalPlayer local char = player.Character or player.CharacterAdded:Wait() --Making the camera scriptable, so we could apply our changes camera.CameraType = Enum.CameraType.Scriptable --Variables local bb = script.Parent.BlueBrick local door = script.Parent.Door local you = script.Parent.You bb.MouseButton1Click:Connect(function() camera.CameraSubject = game.Workspace.BlueBrick end) you.MouseButton1Click:Connect(function() camera.CameraSubject = char.Humanoid or char:WaitForChild("char") end) door.MouseButton1Click:Connect(function() camera.CameraSubject = game.Workspace.Door end) Spectate Players Button --Variables local camera = workspace.CurrentCamera local playersSerivce = game:GetService("Players") local player = playersSerivce.LocalPlayer local char = player.Character or player.CharacterAdded:Wait() local toggle = script.Parent.Spectate local frame = script.Parent.ViewingPlayers local previous = frame.Previous local next = frame.Next --This would help us counting [down/up] when we press previous/next, and get the players. local countingPlayers = 1 toggle.MouseButton1Click:Connect(function() frame.Visible = not frame.Visible frame.PlayerName.Text = player.Name camera.CameraSubject = char end) previous.MouseButton1Click:Connect(function() local players = #playersSerivce:GetPlayers() countingPlayers -= 1 if countingPlayers < 1 then countingPlayers = players end local realPlayer = playersSerivce:GetPlayers()[countingPlayers] camera.CameraSubject = realPlayer.Character.Humanoid frame.PlayerName.Text = realPlayer.Name end) next.MouseButton1Click:Connect(function() local players = #playersSerivce:GetPlayers() countingPlayers += 1 if countingPlayers > players then countingPlayers = 1 end local realPlayer = playersSerivce:GetPlayers()[countingPlayers] camera.CameraSubject = realPlayer.Character.Humanoid frame.PlayerName.Text = realPlayer.Name end) Humanoid/Tools Animation

In this section, we’ll be learning how to apply animations onto tools/player’s character.
When we talk about Animation here, we talk about loading custom/built in movements/actions for our tools/humanoid actions.When you’re testing in studio, you can view under your humanoid, there is an object named Animator. The Animator is the main object that is responsible for the animations you have in your game. There are 2 ways to create this object:
1.Humanoid:LoadAnimation().
2.AnimationController:LoadAnimation().

Important notes:

For animation replication to function it is important for the Animator to be first created on the server.

The Animator object must be initially created on the server and replicated to others for animation replication in order to be shown to all. If the Animator is created locally, then any animation loaded through this animator, won’t replicate to server.

Loading Animation:

You’ll need to use the LoadAnimation() method ,and provide an Animation object [NOT its animationID]. An example:

local UIS = game:GetService('UserInputService') local Players = game:GetService("Players") local Player = Players.LocalPlayer local Character = Player.Character or Player.CharacterAdded:Wait() local Humanoid = Character:WaitForChild("Humanoid") local Anim = Instance.new('Animation') Anim.AnimationId = 'rbxassetid://10910827063' --Start Running Animation UIS.InputBegan:connect(function(input,processed) if processed then return end if input.KeyCode == Enum.KeyCode.LeftShift then Humanoid.WalkSpeed = 24 PlayAnim = Humanoid:LoadAnimation(Anim) PlayAnim:Play() end end) --Stop Running Animation UIS.InputEnded:connect(function(input) if input.KeyCode == Enum.KeyCode.LeftShift then Humanoid.WalkSpeed = 16 if PlayAnim then PlayAnim:Stop() PlayAnim:Destroy() end end end) Mouse & UserInputService

In this section, we’ll be learning about Mouse and UserInputService ; what they are and what they do.

Introduction:

Mouse:
Simply our cursor. We can get the Mouse in this way:

--Local script local Players = game:GetService("Players") local Player = Players.LocalPlayer local Mouse = Player:GetMouse() Notice:

Although Mouse is deprecated [UserInputService and ContextActionService are its replacement],
it is still supported and can be used.

Properties Hit(CFrame)

This property returns the mouse’s position in the 3D space which we work with in studio.

Target(BasePart)

This property returns the 3D object which the mouse is pointing to.
Notice: if you set Mouse.TargetFilter, then all the provided objects within the filter would be ignored.

Events Move

This event fires whenever the mouse is moved.[Only when the mouse’s position is updated/changed].

local Players = game:GetService("Players") local Player = Players.LocalPlayer local Mouse = Player:GetMouse() Mouse.Move:Connect(function() local Target = Mouse.Target print(Target) -- would print nil if pointed to sky end)

UserInputService:
Simply a service used to detect and capture the different types of input available on a user’s device.[Console, Mobile, PC, etc].
Basically, the main purpose of this service is to provide the best experience possible to all possible devices.

Notice:

This service is client-sided only. Meaning, it can only be used on the client. Which obviously means - you can only use it in LocalScript's or in ModuleScript's required by localscripts.

Properties MouseEnabled[boolean]

This property checks if the player’s device has a mouse.[ and returns true if found], if not found - it returns false.

TouchEnabled[boolean]

Simply checks if the player’s device has any available touch screen.
If there is a touch screen found, you could use UserInputService - TouchEnded/TouchStarted events to operate accordingly and detect their behavior on their device.

VREnabled[boolean]

Simply checks if the player is using a VR device. If a VR device was found, you could use some events such as UserInputService:GetUserCFrame() to do some cool stuff with it.

Events InputBegan

This event would run whenever a player begins interacting with one of the following devices [ pc,mobile,console,vr,etc].

local UserInputService = game:GetService("UserInputService") UserInputService.InputBegan:Connect(function(Key,Processed) if Processed then return end -- if I am during chatting, then end the function. print(Key.KeyCode.Name) -- would print the name of the pressed key. end) InputChanged

This would fire everytime the player is changing their interaction type [ for example: Mouse button down].

local UserInputService = game:GetService("UserInputService") UserInputService.InputChanged:Connect(function(Key,Processed) if Processed then return end -- if I am during chatting, then end the function. if Key.UserInputType == Enum.UserInputType.MouseMovement then print("The Mouse has been moved!") end end)

Here is Part2, since I couldnt fit it in the original post because of a limit.

(责任编辑:)
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:
发布者资料
查看详细资料 发送留言 加为好友 用户等级: 注册时间:2025-10-14 07:10 最后登录:2025-10-14 07:10
栏目列表
推荐内容