Hello,
The title is a bit vague, what i want to know what the best and optimal way is to handle character movement, but not only movement, just character related things in generall. What do i mean by that?
Lets say i have 3 localscripts,
- running
- roll
- dashing
Normally, with the current knowledge i would just create 3 local scripts and then put them in startercharacterscripts. But thats seems kinda unnecessary, because i would need to make 3 different scripts and all need to have the same lines of code over and over again
Example
We can see in this image i have 3 scripts as stated before the drop down.
In all of these scripts i have this typed:
local plrs = game:GetService('Players')
local plr = plrs.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local hum = char:FindFirstChildWhichIsA("Humanoid")
My attempt
local runner = {}
runner.__index = runner
local runSpeed = 30
local cas = game:GetService("ContextActionService")
local runKeybind = Enum.KeyCode.LeftShift
local ll = "Run"
function runner.new(char:Model)
local hum = char:FindFirstChildWhichIsA("Humanoid")
local self = setmetatable({}, runner)
self.oldSpeed = hum.WalkSpeed
self.running = false
self.hum = hum
local function handler(_, state)
if state == Enum.UserInputState.Begin then
runner:Run()
elseif state == Enum.UserInputState.End then
runner:UnRun()
end
end
cas:BindAction(ll, handler, true, runKeybind)
return self
end
function runner:Run()
self.hum.WalkSpeed = runSpeed
end
function runner:UnRun()
self.hum.WalkSpeed = self.oldSpeed
end
function runner:Disconnect()
cas:UnbindAction(ll)
end
return runner
This module script didnt work as i wanted, and instead bonked me in the head with this error: 20:52:14.171 Workspace.3Xp01tME.charmovement.run:33: attempt to index nil with 'WalkSpeed' - Client - run:33
Second attempt (successfull)
I did it with module script.
local runner = {}
runner.__index = runner
local runSpeed = 30
local cas = game:GetService("ContextActionService")
function runner.new(char:Model, ll)
local hum = char:FindFirstChildWhichIsA("Humanoid")
local self = setmetatable({}, runner)
self.oldSpeed = hum.WalkSpeed
self.running = false
self.hum = hum
self.ll = ll
return self
end
function runner:RunHandler()
local function handler(actionName, inputState, inputObject)
if inputState == Enum.UserInputState.Begin then
self:Run()
elseif inputState == Enum.UserInputState.End then
self:UnRun()
end
end
cas:BindAction(self.ll, handler, true, Enum.KeyCode.LeftShift)
end
function runner:Run()
self.hum.WalkSpeed = runSpeed
end
function runner:UnRun()
self.hum.WalkSpeed = self.oldSpeed
end
function runner:Disconnect()
cas:UnbindAction(self.ll)
end
return runner
My initial thoughts was to use module scripts and then have 1 local script that handles the module scripts, but i dont know how i would make that happen. I would like to hear yall thoughts, or maybe how you do it.
Thanks.