There are many situations where I need to turn the player first person throughout many scripts, so I decided that this would be most effective with a module script. It does work, but I want to know if this is the most efficient way to compile the module script.
local module = {}
function module.firstPerson()
local WS = game:GetService("Workspace")
local Players = game:GetService("Players")
local ContextActionService = game:GetService("ContextActionService")
local Lighting = game:GetService("Lighting")
local player = Players.LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
local hum = char:FindFirstChild("Humanoid") or char:WaitForChild("Humanoid")
local camera = WS.CurrentCamera
local head = char:FindFirstChild("Head") or char:WaitForChild("Head")
camera.CameraSubject = char
camera.CFrame = head.CFrame
hum.WalkSpeed = 16
hum.JumpPower = 50
camera.FieldOfView = 70
camera.DiagonalFieldOfView = 126.595
camera.MaxAxisFieldOfView = 101.495
Lighting.FogEnd = 75
ContextActionService:UnbindAction("NoDrag")
player:WaitForChild("Cam").Value = "f"
end
return module
Create Service variables at the top of the module so you don’t have to type it again for other functions: (and it saves like 0.00001 seconds of runtime)
local WS = game:GetService("Workspace")
local Players = game:GetService("Players")
local ContextActionService = game:GetService("ContextActionService")
local Lighting = game:GetService("Lighting")
local module = {}
function module.FirstPerson()
--(...)-- Rest of the code
Set every local variable to nil at the end of the function to save memory:
Thanks so much. Hypothetically, if the variables are defined in a script that you are using the module function in, would you be able to use the variables from that script for the module? For example, there is a script that already localizes head, camera, hum, and everything else, and you want to use the module function inside this script that already has these things as variables. Is there any way to do that?
I don’t think there is a way to do it using local variables, every script has its own local variables and they can be accessed only in that spesific script.
But you can make the variables global using _G
Example:
Ahh I understand. I will try to refrain from using global variables because I heard they aren’t very good, so J will continue will the info you gave me. Thanks so much.