How to make a base system? -- Roblox Lua - lua

I'm trying to make a system to which when the player joins they are given a base and then no other players can use that base.
Here is my module inside the parented to the script:
local Functions = {}
function Functions.findOpenBase(plr)
local bases = workspace.Bases
for i,v in pairs(bases:GetChildren()) do
if v:IsA("Part") then
print("Searching..")
if plr.alreadyOwnsBase.Value == false then
if v.Owner.Value ~= nil then
print("Base found!")
v.Owner.Value = plr.Name
plr.alreadyOwnsBase.Value = true
else
warn("error")
plr:Kick("error finding base, Please Rejoin.")
end
end
else
print("cannot claim another base")
end
end
end
return Functions
then here is my handler script:
local module = require(script.Functions)
game.Players.PlayerAdded:Connect(function(plr)
local alreadyOwnsBase = Instance.new("BoolValue", plr)
alreadyOwnsBase.Name = "alreadyOwnsBase"
alreadyOwnsBase.Value = false
if plr then
module.findOpenBase(plr)
print(plr.Name)
end
end)
is there any solutions?

To me, module inside the parented to the script:
local Functions = {}
function Functions.findOpenBase(plr)
-- check it first.
if plr.alreadyOwnsBase.Value == false then
local bases = workspace.Bases
for i,v in pairs(bases:GetChildren()) do
print("Searching..")
if v:IsA("Part") then
if v.Owner.Value ~= nil then
print("Base found!")
v.Owner.Value = plr.Name
plr.alreadyOwnsBase.Value = true
-- get it, jump the loop
break
end
else
print("cannot claim another base")
end
end
end
-- and plr.alreadyOwnsBase.Value is the flag of the result
if plr.alreadyOwnsBase.Value == false then
warn("error")
plr:Kick("error finding base, Please Rejoin.")
end
end
return Functions
and the handler script:
local module = require(script.Functions)
game.Players.PlayerAdded:Connect(function(plr)
local alreadyOwnsBase = Instance.new("BoolValue", plr)
alreadyOwnsBase.Name = "alreadyOwnsBase"
alreadyOwnsBase.Value = false
if plr then
module.findOpenBase(plr)
-- check the flag
if plr.alreadyOwnsBase.Value then
print(plr.Name)
end
end
end)

Related

(Help) How to make the script below can be re run after respawn?

So, i am trying to make it can be re run after respawn but it does not work, i am kept
struggling.
My purpose with this script (autofarm, when the tween is done, it does waiting until respawn, when it's respawned, it does re run.)
local function teleport()
local teleport_table = {
location1 = Vector3.new(-70, 69, 83), -- Starter Map
location2 = Vector3.new(-68, 69, 9255), -- Tweening map until above end ches
location3 = Vector3.new(-54, -303, 9496) --to chest
}
local tween_s = game:GetService('TweenService')
local tweeninfo1 = TweenInfo.new(1,Enum.EasingStyle.Linear)
local tweeninfo2 = TweenInfo.new(20,Enum.EasingStyle.Linear)
local tweeninfo3 = TweenInfo.new(1,Enum.EasingStyle.Linear)
local lp = game.Players.LocalPlayer
local function teleport()
if not lp.Character or not lp.Character:FindFirstChild('HumanoidRootPart') then
print("Player character not found")
return
end
function tp3_teleport(v)
if not teleport_table[v] then
print("Invalid location")
return
end
local cf = CFrame.new(teleport_table[v])
local a = tween_s:Create(lp.Character.HumanoidRootPart,tweeninfo3,{CFrame=cf})
a:Play()
while a.PlaybackState == Enum.PlaybackState.Playing do
wait()
end
end
function tp2_teleport(v)
if not teleport_table[v] then
print("Invalid location")
return
end
local cf = CFrame.new(teleport_table[v])
local a = tween_s:Create(lp.Character.HumanoidRootPart,tweeninfo2,{CFrame=cf})
a:Play()
while a.PlaybackState == Enum.PlaybackState.Playing do
wait()
end
tp3_teleport("location3")
end
function tp1_teleport(v)
if not teleport_table[v] then
print("Invalid location")
return
end
local cf = CFrame.new(teleport_table[v])
local a = tween_s:Create(lp.Character.HumanoidRootPart,tweeninfo1,{CFrame=cf})
a:Play()
while a.PlaybackState == Enum.PlaybackState.Playing do
wait()
end
tp2_teleport("location2")
end
tp1_teleport("location1")
end
game.Players.PlayerAdded:Connect(function(player)
if player == game.Players.LocalPlayer then
teleport()
end
end)
I am kept trying to make it run, but also re run after respawn when the script is done and i am kept making and asking ChatGPT which resulted helpless for me.
Changing few last lines to this should work
game.Players.PlayerAdded:Connect(function(player)
if player == game.Players.LocalPlayer then
teleport()
player.CharacterAdded:Connect(function()
teleport()
end)
end
end)

If i unequip a gun while it's shooting (in burst and auto) it stops working -ROBLOX STUDIO

Pls find a way to fix it :/ I'm not really good at scripting stuff.
There is another script: Server script. But i don't think it's the cause of this problem.
I will post it anyways
Btw it's for a shooter game that I'm making (just to add some workds soo i can post it)
When it breaks it send's out this:
 19:31:45.103 Humanoid is not a valid member of Backpack "Players.xxfilippoxx33.Backpack"  -  Client  -  Gun_Script:178
  19:31:45.103 Stack Begin  -  Studio
  19:31:45.103 Script 'Players.xxfilippoxx33.Backpack.Assualt Rifle.Gun_Script', Line 178 - function fire  -  Studio  -  Gun_Script:178
  19:31:45.104 Script 'Players.xxfilippoxx33.Backpack.Assualt Rifle.Gun_Script', Line 314 - function onButton1Down  -  Studio  -  Gun_Script:314
  19:31:45.104 Script 'Players.xxfilippoxx33.Backpack.Assualt Rifle.Gun_Script', Line 367  -  Studio  -  Gun_Script:367
  19:31:45.104 Stack End  -  Studio
Here is the local script
--// Created by Nightrains
local localPlayer = game.Players.LocalPlayer
local sp = script.Parent
--// Wait For Children
sp:WaitForChild("Handle")
sp:WaitForChild("Ammo")
sp.Handle:WaitForChild("Equip")
sp.Handle:WaitForChild("Fire")
sp.Handle:WaitForChild("Reload")
sp.Handle:WaitForChild("Trigger")
sp.Handle:WaitForChild("PointLight")
--// Gun Configuration
local CanTeamkill = false
local FirstPersonArms = true
local HeadshotDamage = true
local IgnoreHats = true
local ClipSize=30
local ReloadTime=2.3
local Firerate=.3
local MinSpread=0.15
local MaxSpread=0.15
local SpreadRate=0.3
local BaseDamage= 20
local Spread=0.15
local automatic=false
local burst=true
local shot=false --Shotgun
local BarrlePos=Vector3.new(-2.5,.60,0)
local Cursors={"rbxasset://textures\\GunCursor.png"}
local ReloadCursor="rbxasset://textures\\GunWaitCursor.png"
-------------------------------------
local equiped=false
local enabled=true
local reloading=false
local down=false
local r=game:service("RunService")
local Bullet=Instance.new("Part")
Bullet.Name="Bullet"
Bullet.BrickColor=BrickColor.new("Bright yellow")
Bullet.Anchored=true
Bullet.CanCollide=false
Bullet.Locked=true
Bullet.Size=Vector3.new(1,1,1)
Bullet.formFactor=0
Bullet.TopSurface=0
Bullet.BottomSurface=0
Bullet.Material = Enum.Material.Neon
local Mesh=Instance.new("SpecialMesh")
Mesh.Parent=Bullet
Mesh.MeshType="Brick"
Mesh.Name="Mesh"
Mesh.Scale=Vector3.new(.15,.15,1)
local pointLight = sp.Handle.PointLight
local Debris = game:GetService("Debris")
local gunServer = game:GetService("ReplicatedStorage"):WaitForChild("GunRemotes")
local remote = {
TagHumanoid = gunServer:WaitForChild("TagHumanoid"),
FireServer = gunServer:WaitForChild("FireServer"),
TakeDamage = gunServer:WaitForChild("TakeDamage"),
PlaySound = gunServer:WaitForChild("PlaySound"),
}
local ContextActionService = game:GetService("ContextActionService")
-------------------------------------------------------------------------------
game.Workspace.ChildAdded:Connect(function(child)
if child.Name == localPlayer.Name.."Bullet" then
child.Transparency = 1
end
end)
local function reload(mouse)
remote.PlaySound:FireServer(sp.Handle.Reload)
reloading=true
mouse.Icon=ReloadCursor
while sp.Ammo.Value<ClipSize and reloading and enabled do
wait(ReloadTime/ClipSize)
if reloading then
sp.Ammo.Value=sp.Ammo.Value+1
else
break
end
end
mouse.Icon=Cursors[1]
reloading=false
end
local function reload_Mob()
remote.PlaySound:FireServer(sp.Handle.Reload)
reloading=true
while sp.Ammo.Value<ClipSize and reloading and enabled do
wait(ReloadTime/ClipSize)
if reloading then
sp.Ammo.Value=sp.Ammo.Value+1
else
break
end
end
reloading=false
end
script.Parent.Equipped:Connect(function()
ContextActionService:SetPosition("ReloadButton",UDim2.new(0.72,-25,0.20,-25))
end)
script.Parent.Unequipped:Connect(function()
ContextActionService:SetPosition("ReloadButton",UDim2.new(2.72,-9,0.20,-80))
end)
local function onKeyDown(key,mouse)
key=key:lower()
if key=="r" and not reloading then
reload(mouse)
end
end
function onButtonPress()
wait(0.1)
if onButtonPress() and not reloading then
if script.Parent.Ammo.Value < 30 then
wait(0.1)
reload_Mob()
end
script.Parent:reload(button)
end
end
local mobilebutton = ContextActionService:BindAction("ReloadButton",onButtonPress,true,"R")
ContextActionService:SetPosition("ReloadButton",UDim2.new(2.72,-90,.20,-25))
local function getIgnoreList()
local list = {localPlayer.Character}
for _,child in pairs(game.Workspace:GetDescendants()) do
if child:IsA("BasePart") then
if not child.CanCollide then
if child.Name == "Handle" and IgnoreHats then
table.insert(list,child)
elseif child.Name ~= "Handle" and not child.Parent:FindFirstChild("Humanoid") then
table.insert(list,child)
end
end
end
end
return list
end
local function bulletEffect(bullet,distance)
if distance > 40 then
local bulletLength = distance/2
bullet.Mesh.Scale=Vector3.new(.15,.15,bulletLength)
bullet.Mesh.Offset=Vector3.new(0,0,bulletLength/2)
while bullet.Mesh.Offset.Z > (bulletLength/2)*-1 do
wait()
bullet.Mesh.Offset=Vector3.new(0,0,bullet.Mesh.Offset.Z-20)
end
else
bullet.Mesh.Scale=Vector3.new(.15,.15,distance)
bullet.Mesh.Offset=Vector3.new(0,0,distance/2)
wait(0.03)
end
bullet:Destroy()
end
local function fire(aim)
if sp.Parent.Humanoid.Health < 1 then
return
end
remote.PlaySound:FireServer(sp.Handle.Fire)
t=r.Stepped:wait()
last6=last5
last5=last4
last4=last3
last3=last2
last2=last
last=t
local bullet=Bullet:clone()
local startpoint=sp.Handle.CFrame*BarrlePos
local ray = Ray.new(startpoint, (aim - startpoint).unit * 300)
local hit, position = workspace:FindPartOnRayWithIgnoreList(ray, getIgnoreList(), false, true)
local distance = (startpoint - position).magnitude
bullet.Parent=game.Workspace.CurrentCamera
remote.FireServer:FireServer(startpoint,position,pointLight)
if hit~=nil then
local humanoid=hit.Parent:FindFirstChild("Humanoid")
if not humanoid then
humanoid = hit.Parent.Parent:FindFirstChild("Humanoid")
end
if humanoid~=nil then
local damage=math.random(BaseDamage-(BaseDamage*.25),BaseDamage+(BaseDamage*.25))
local headshot = false
if hit.Name=="Head" and HeadshotDamage then
damage=damage*1.3
--headshot = true
else
damage=damage*.75
end
if humanoid.Health>0 then
local eplr=game.Players:playerFromCharacter(humanoid.Parent)
local plr=game.Players:playerFromCharacter(sp.Parent)
if eplr~=nil and plr~=nil then
if CanTeamkill then
remote.TagHumanoid:FireServer(humanoid)
remote.TakeDamage:FireServer(humanoid,damage,headshot)
else
if eplr.TeamColor~=plr.TeamColor or eplr.Neutral or plr.Neutral then
remote.TagHumanoid:FireServer(humanoid)
remote.TakeDamage:FireServer(humanoid,damage,headshot)
end
end
else
remote.TagHumanoid:FireServer(humanoid)
remote.TakeDamage:FireServer(humanoid,damage,headshot)
end
end
end
end
if distance > 40 then
bullet.CFrame=CFrame.new(startpoint, position) * CFrame.new(0, 0, -distance / 2)
else
bullet.CFrame=CFrame.new(startpoint, position) * CFrame.new(0, 0, -distance)
end
spawn(function()
bulletEffect(bullet,distance)
end)
end
local ObjectLocalTransparencyModifier
local RunService = game:GetService("RunService")
local LocalObjects = {}
local function setArmsTransparency(Limb)
if FirstPersonArms then
local value = {Object = Limb, Transparency = 0, AutoUpdate = true}
pcall(function()
local ObjectFound = false
for i, v in pairs(LocalObjects) do
if v == value then
ObjectFound = true
end
end
if not ObjectFound then
table.insert(LocalObjects, value)
if ObjectLocalTransparencyModifier then
ObjectLocalTransparencyModifier:disconnect()
end
ObjectLocalTransparencyModifier = RunService.RenderStepped:connect(function()
local Camera = game:GetService("Workspace").CurrentCamera
for i, v in pairs(LocalObjects) do
if v.Object and v.Object.Parent then
local CurrentTransparency = v.Object.LocalTransparencyModifier
local ViewDistance = (Camera.CoordinateFrame.p - sp.Parent.Head.Position).Magnitude
if ((not v.AutoUpdate and (CurrentTransparency == 1 or CurrentTransparency == 0)) or v.AutoUpdate) then
if ((v.Distance and ViewDistance <= v.Distance) or not v.Distance) then
v.Object.LocalTransparencyModifier = v.Transparency
else
v.Object.LocalTransparencyModifier = 0
end
end
else
table.remove(LocalObjects, i)
end
end
end)
end
end)
end
end
local function onButton1Up(mouse)
down=false
end
local function onButton1Down(mouse)
local h=sp.Parent:FindFirstChild("Humanoid")
if not enabled or reloading or down or h==nil then
return
end
if sp.Ammo.Value>0 and h.Health>0 then
down=true
enabled=false
while down do
if sp.Ammo.Value<=0 then
break
end
if burst then
local startpoint=sp.Handle.CFrame*BarrlePos
local mag=(mouse.Hit.p-startpoint).magnitude
local rndm=Vector3.new(math.random(-(Spread/10)*mag,(Spread/10)*mag),math.random(-(Spread/10)*mag,(Spread/10)*mag),math.random(-(Spread/10)*mag,(Spread/10)*mag))
fire(mouse.Hit.p+rndm)
sp.Ammo.Value=sp.Ammo.Value-1
if sp.Ammo.Value<=0 then
break
end
wait(.05)
local startpoint=sp.Handle.CFrame*BarrlePos
local mag2=((mouse.Hit.p+rndm)-startpoint).magnitude
local rndm2=Vector3.new(math.random(-(.1/10)*mag2,(.1/10)*mag2),math.random(-(.1/10)*mag2,(.1/10)*mag2),math.random(-(.1/10)*mag2,(.1/10)*mag2))
fire(mouse.Hit.p+rndm+rndm2)
sp.Ammo.Value=sp.Ammo.Value-1
if sp.Ammo.Value<=0 then
break
end
wait(.05)
fire(mouse.Hit.p+rndm+rndm2+rndm2)
sp.Ammo.Value=sp.Ammo.Value-1
elseif shot then
sp.Ammo.Value=sp.Ammo.Value-1
local startpoint=sp.Handle.CFrame*BarrlePos
local mag=(mouse.Hit.p-startpoint).magnitude
local rndm=Vector3.new(math.random(-(Spread/10)*mag,(Spread/10)*mag),math.random(-(Spread/10)*mag,(Spread/10)*mag),math.random(-(Spread/10)*mag,(Spread/10)*mag))
fire(mouse.Hit.p+rndm)
local mag2=((mouse.Hit.p+rndm)-startpoint).magnitude
local rndm2=Vector3.new(math.random(-(.2/10)*mag2,(.2/10)*mag2),math.random(-(.2/10)*mag2,(.2/10)*mag2),math.random(-(.2/10)*mag2,(.2/10)*mag2))
fire(mouse.Hit.p+rndm+rndm2)
local rndm3=Vector3.new(math.random(-(.2/10)*mag2,(.2/10)*mag2),math.random(-(.2/10)*mag2,(.2/10)*mag2),math.random(-(.2/10)*mag2,(.2/10)*mag2))
fire(mouse.Hit.p+rndm+rndm3)
local rndm4=Vector3.new(math.random(-(.2/10)*mag2,(.2/10)*mag2),math.random(-(.2/10)*mag2,(.2/10)*mag2),math.random(-(.2/10)*mag2,(.2/10)*mag2))
fire(mouse.Hit.p+rndm+rndm4)
else
sp.Ammo.Value=sp.Ammo.Value-1
local startpoint=sp.Handle.CFrame*BarrlePos
local mag=(mouse.Hit.p-startpoint).magnitude
local rndm=Vector3.new(math.random(-(Spread/10)*mag,(Spread/10)*mag),math.random(-(Spread/10)*mag,(Spread/10)*mag),math.random(-(Spread/10)*mag,(Spread/10)*mag))
fire(mouse.Hit.p+rndm)
end
wait(Firerate)
if not automatic then
break
end
end
enabled=true
else
remote.PlaySound:FireServer(sp.Handle.Trigger)
end
end
local function onEquippedLocal(mouse)
remote.PlaySound:FireServer(sp.Handle.Equip)
if mouse==nil then
print("Mouse not found")
return
end
local Limbs = {"Right Arm", "RightHand", "RightUpperArm", "RightLowerArm",
"Left Arm", "LeftHand", "LeftUpperArm", "LeftLowerArm"}
for i, v in pairs(Limbs) do
local Limb = sp.Parent:FindFirstChild(v)
setArmsTransparency(Limb)
end
mouse.Icon=Cursors[1]
mouse.KeyDown:connect(function(key) onKeyDown(key,mouse) end)
mouse.Button1Down:connect(function() onButton1Down(mouse) end)
mouse.Button1Up:connect(function() onButton1Up(mouse) end)
equiped=true
if #Cursors>1 then
while equiped do
t=r.Stepped:wait()
local action=sp.Parent:FindFirstChild("Pose")
if action~=nil then
if sp.Parent.Pose.Value=="Standing" then
Spread=MinSpread
else
Spread=MinSpread+((4/10)*(MaxSpread-MinSpread))
end
else
Spread=MinSpread
end
if t-last<SpreadRate then
Spread=Spread+.1*(MaxSpread-MinSpread)
end
if t-last2<SpreadRate then
Spread=Spread+.1*(MaxSpread-MinSpread)
end
if t-last3<SpreadRate then
Spread=Spread+.1*(MaxSpread-MinSpread)
end
if t-last4<SpreadRate then
Spread=Spread+.1*(MaxSpread-MinSpread)
end
if t-last5<SpreadRate then
Spread=Spread+.1*(MaxSpread-MinSpread)
end
if t-last6<SpreadRate then
Spread=Spread+.1*(MaxSpread-MinSpread)
end
if not reloading then
local percent=(Spread-MinSpread)/(MaxSpread-MinSpread)
for i=0,#Cursors-1 do
if percent>(i/(#Cursors-1))-((1/(#Cursors-1))/2) and percent<(i/(#Cursors-1))+((1/(#Cursors-1))/2) then
mouse.Icon=Cursors[i+1]
end
end
end
wait(Firerate*.9)
end
end
end
local function onUnequippedLocal(mouse)
if ObjectLocalTransparencyModifier then
ObjectLocalTransparencyModifier:disconnect()
end
local camera = game.Workspace.CurrentCamera
if (camera.focus.p - camera.CoordinateFrame.p).magnitude <= 1 then
for i, v in pairs(LocalObjects) do
if v.Object then
v.Object.LocalTransparencyModifier = 1
end
end
end
LocalObjects = {}
equiped=false
reloading=false
end
sp.Equipped:connect(onEquippedLocal)
sp.Unequipped:connect(onUnequippedLocal)
SERVER SCRIPT
--PUT ME IN ServerScriptService.
local replicatedStorage = game.ReplicatedStorage
local debris = game:GetService("Debris")
local folder = Instance.new("Folder",replicatedStorage)
folder.Name = "GunRemotes"
local Bullet=Instance.new("Part")
Bullet.Name="Bullet"
Bullet.BrickColor=BrickColor.new("Bright yellow")
Bullet.Anchored=true
Bullet.CanCollide=false
Bullet.Locked=true
Bullet.Size=Vector3.new(1,1,1)
Bullet.formFactor=0
Bullet.TopSurface=0
Bullet.BottomSurface=0
Bullet.Transparency = 1
Bullet.Material = Enum.Material.Neon
local Mesh=Instance.new("SpecialMesh")
Mesh.Parent=Bullet
Mesh.MeshType="Brick"
Mesh.Name="Mesh"
Mesh.Scale=Vector3.new(.15,.15,1)
local function remote(name)
local create = Instance.new("RemoteEvent",folder)
create.Name = name
return create
end
local fireServer = remote("FireServer")
fireServer.OnServerEvent:connect(function(player,startpoint,pos)
local newBullet = Bullet:Clone()
newBullet.Name = player.Name.."Bullet"
local distance=(startpoint-pos).magnitude
local bulletLength = distance/2
if distance > 40 then
newBullet.CFrame=CFrame.new(startpoint, pos) * CFrame.new(0, 0, -distance / 2)
newBullet.Mesh.Scale=Vector3.new(.15,.15,bulletLength)
newBullet.Mesh.Offset=Vector3.new(0,0,bulletLength/2)
else
newBullet.CFrame=CFrame.new(startpoint, pos) * CFrame.new(0, 0, -distance)
newBullet.Mesh.Scale=Vector3.new(.15,.15,distance)
newBullet.Mesh.Offset=Vector3.new(0,0,distance/2)
end
newBullet.Transparency = 0
newBullet.Parent = game.Workspace
if distance > 40 then
while newBullet.Mesh.Offset.Z > (bulletLength/2)*-1 do
wait()
newBullet.Mesh.Offset=Vector3.new(0,0,newBullet.Mesh.Offset.Z-20)
end
else
wait(0.03)
end
newBullet:Destroy()
end)
fireServer.OnServerEvent:connect(function(_,_,_,light)
light.Enabled = true
wait(.05)
light.Enabled = false
end)
remote("TagHumanoid").OnServerEvent:connect(function(player,humanoid)
local tag = Instance.new("ObjectValue")
tag.Value = player
tag.Name = "creator"
tag.Parent = humanoid
delay(2,function()
if tag ~= nil then
tag.Parent = nil
end
end)
end)
remote("TakeDamage").OnServerEvent:connect(function(player,humanoid,damage,head)
humanoid:TakeDamage(damage)
if humanoid.Health < 1 and head then
humanoid.Parent.Head:Destroy()
end
end)
remote("PlaySound").OnServerEvent:connect(function(player,sound)
sound:Play()
end)
remote("HumanoidSpeed").OnServerEvent:connect(function(player,humanoid,speed)
humanoid.WalkSpeed = speed
end)
The error message says:
Humanoid is not a valid member of Backpack
Script 'Players.xxfilippoxx33.Backpack.Assualt Rifle.Gun_Script', Line 178 - function fire
local function fire(aim)
if sp.Parent.Humanoid.Health < 1 then
return
end
....
sp.Parent.Humanoid does not exist. So you may not use it.
Additional comment:
local humanoid=hit.Parent:FindFirstChild("Humanoid")
if not humanoid then
humanoid = hit.Parent.Parent:FindFirstChild("Humanoid")
end
If there is no child "Humanoid" there is no point in trying it again.

Why do I keep getting the error "attempt to index nil with 'Cash' in my script?

For a bit of context, I'm making a Tycoon on Roblox to test my knowledge in lua. Everything was working fine until I tried making leaderstats. The first script, which is what makes the Tycoon
function, is here:
local TycoonInfo = script.Parent:WaitForChild("TycoonInfo")
local OwnerValue = TycoonInfo:WaitForChild("Owner")
local Buttons = script.Parent:WaitForChild("Buttons")
local Purchases = script.Parent:WaitForChild("Purchases")
local Objects = {}
function validateHitByOwner(Hit)
if Hit and Hit.Parent and Hit.Parent:FindFirstChild("Humanoid") then
local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
if Player and OwnerValue.Value== Player then
return true
end
end
return false
end
for i,v in pairs(Buttons:GetChildren()) do
local Object = Purchases:FindFirstChild(v.Object.Value)
if Object then
Objects[Object.Name] = Object:Clone()
Object:Destroy()
if v:FindFirstChild("Dependency") then
coroutine.resume(coroutine.create(function()
v.Button.Transparency = 1
v.Button.BillboardGui.Enabled = false
v.Button.CanCollide = false
if Purchases:WaitForChild(v.Dependency.Value,90000) then
v.Button.Transparency = 0
v.Button.CanCollide = true
v.Button.BillboardGui.Enabled = true
end
end))
end
local DB = false
v.Button.Touched:Connect(function(Hit)
if validateHitByOwner(Hit)then
if DB == false then
DB = true
if v.Button.Transparency == 0 then
local Purchased = DoPurchase(Hit,v,v.Price.Value,Objects[v.Object.Value])
if Purchased then
warn("Purchased")
else
warn("Can't purchase")
end
end
DB = false
end
end
end)
end
end
function DoPurchase(Hit,Button,Cost,Object)
if Hit and Hit.Parent and Hit.Parent:FindFirstChild("Humanoid") then
local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
if Player and OwnerValue.Value == Player then
local name = game.Players:GetChildren()
local CashValue = game.Players.name.leaderstats.Cash -- Error here
if CashValue then
if CashValue.Value >= Cost then
CashValue.Value = CashValue.Value - Cost
Object.Parent = Purchases
Button:Destroy()
return true
end
end
end
end
return false
end
The next script, which makes the leaderboard and assigns a player that has recently joined to a random available Tycoon, is here:
function FindEmptyTycoon()
for i,v in pairs(workspace.Tycoons:GetChildren()) do
if v.TycoonInfo.Owner.Value == nil then
return v
end
end
return nil
end
game.Players.PlayerAdded:Connect(function(Player)
local Tycoon = FindEmptyTycoon()
Tycoon.TycoonInfo.Owner.Value = Player
local stats = Instance.new("Folder",Player)
stats.Name = "leaderstats"
local Cash = Instance.new("IntValue",stats)
Cash.Name = "Cash"
end)
And then, the script that is stored in all purchasable items to give the Player money, is here:
function giveCash(player)
wait(3.33)
local Cash = player.leaderstats.Cash
Cash.Value = Cash.Value + 2
end
By the way, these scripts are versions of the original scripts that I've been trying to edit so they can actually work, and I think I've been getting close to fixing the errors. The original scripts can be found here (in order of appearance):
local TycoonInfo = script.Parent:WaitForChild("TycoonInfo")
local OwnerValue = TycoonInfo:WaitForChild("Owner")
local Buttons = script.Parent:WaitForChild("Buttons")
local Purchases = script.Parent:WaitForChild("Purchases")
local Objects = {}
function validateHitByOwner(Hit)
if Hit and Hit.Parent and Hit.Parent:FindFirstChild("Humanoid") then
local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
if Player and OwnerValue.Value== Player then
return true
end
end
return false
end
for i,v in pairs(Buttons:GetChildren()) do
local Object = Purchases:FindFirstChild(v.Object.Value)
if Object then
Objects[Object.Name] = Object:Clone()
Object:Destroy()
if v:FindFirstChild("Dependency") then
coroutine.resume(coroutine.create(function()
v.Button.Transparency = 1
v.Button.BillboardGui.Enabled = false
v.Button.CanCollide = false
if Purchases:WaitForChild(v.Dependency.Value,90000) then
v.Button.Transparency = 0
v.Button.CanCollide = true
v.Button.BillboardGui.Enabled = true
end
end))
end
local DB = false
v.Button.Touched:Connect(function(Hit)
if validateHitByOwner(Hit)then
if DB == false then
DB = true
if v.Button.Transparency == 0 then
local Purchased = DoPurchase(Hit,v,v.Price.Value,Objects[v.Object.Value])
if Purchased then
warn("Purchased")
else
warn("Can't purchase")
end
end
DB = false
end
end
end)
end
end
function DoPurchase(Hit,Button,Cost,Object)
if Hit and Hit.Parent and Hit.Parent:FindFirstChild("Humanoid") then
local Player = game.Players:GetPlayerFromCharacter(Hit.Parent)
if Player and OwnerValue.Value == Player then
local CashValue = game.ServerStorage.PlayerCash:FindFirstChild(Player.Name)
if CashValue then
if CashValue.Value >= Cost then
CashValue.Value = CashValue.Value - Cost
Object.Parent = Purchases
Button:Destroy()
return true
end
end
end
end
return false
end
function FindEmptyTycoon()
for i,v in pairs(workspace.Tycoons:GetChildren()) do
if v.TycoonInfo.Owner.Value == nil then
return v
end
end
return nil
end
game.Players.PlayerAdded:Connect(function(Player)
local Tycoon = FindEmptyTycoon()
Tycoon.TycoonInfo.Owner.Value = Player
local stats = Instance.new("BoolValue",Player)
stats.Name = "leaderstats"
stats.Parent = game.ServerStorage
local Cash = Instance.new("IntValue",stats)
Cash.Name = Player.Name
Cash.Value = 0
Cash.Parent = game.ServerStorage.PlayerCash
end)
local amount = 2
local timedelay = 2.33
local currencyname = "Cash"
wait(1)
while true do
wait(timedelay)
for i,v in pairs(game.ServerStorage.PlayerCash:GetChildren()) do
if v:FindFirstChild("leaderstats") and v then
v.leaderstats[currencyname].Value = v.leaderstats[currencyname].Value + amount
end
end
end
local name = game.Players:GetChildren()
Why do you store the list of Players's children in a variable called name? This function returns a table. name would be more suitable for a string.
local CashValue = game.Players.name.leaderstats.Cash -- Error here
game.Players is https://developer.roblox.com/en-us/api-reference/class/Players
I cannot make sense of game.Players.name and even less of game.Players.name.leaderstats
Did you mean Player.leaderstats?
I would expect an error message for Players.name.leaderstats before facing an error for game.Players.name.leaderstats.Cash
name is not a Property of Players so you should not be allowed to index Players.name
I'm no Roblox expert but from what I see your code is so off that you really should start with simple tutorials rather than with fixing this code.
I think you should start over and make sure you understand how Instance.new is used properly and such things.
Using better variable names will also help.

Roblox Lua cannot access modulescript function

I've been trying to connect a ModuleScript to a server Script, and it's throwing the error: Workspace.Script:6: attempt to call field 'check3' (a nil value)
ModuleScript
local GunStats = {}
local part = workspace:WaitForChild('Mosin'):WaitForChild("Union")
local billboard = workspace:WaitForChild('BillboardPart'):WaitForChild('BillboardGui')
local uis = game:GetService("UserInputService")
local Ekey = Enum.KeyCode.E
local check = false
local start = tick()
local function onpress(action1)
if check then
part.BrickColor = BrickColor.new("Black")
end
end
local function isKeydown(startTime)
return uis:IsKeyDown(startTime) and startTime - tick() <= 5
end
local function Input(input, gameprocessed)
if isKeydown(Ekey) then
print("h")
else
print("n")
end
start = tick()
end
game.Players.PlayerAdded:Connect(function(player)
local character = player.Character or player.CharacterAdded:Wait()
local humRoot = character:WaitForChild("HumanoidRootPart")
uis.InputBegan:Connect(Input)
GunStats.check3 = function()
while wait() do
if (humRoot.Position - part.Position).Magnitude < 5 then
print("IN RANGE")
check = true
billboard.Enabled = true
repeat wait() until (humRoot.Position - part.Position).Magnitude >= 5
elseif (humRoot.Position - part.Position).Magnitude > 5 and check then
check = false
print("OUT OF")
billboard.Enabled = false
end
end
end
end)
return GunStats
Server Script:
local players = game:GetService("Players")
local serverStorage = game.ServerStorage
local gunStats = require(serverStorage:WaitForChild("ModuleScript"))
game.Players.PlayerAdded:Connect(function(players)
gunStats.check3(players)
end)
This issue is because the gunStats.check3() function isn't defined on the GunStats object until after a player joins. I would restructure your ModuleScript so that GunStats.check3() is defined right away :
--[[ define all your helper functions up here ... ]]
local GunStats = {}
function GunStats.check3(player)
-- access the humanoid
local character = player.Character or player.CharacterAdded:Wait()
local humRoot = character:WaitForChild("HumanoidRootPart")
-- do the checks
end
return GunStats

Disable lasers instead of being enabled? (ROBLOX Lua)

Hey stackoverflow community. So I have started working on a "Tycoon" in ROBLOX. I have gathered a couple custom models but I ran into an issue with one of them. Basically, I want a laser gate for each player base. The problem I have is that the lasers from the laser gate are enabled at the beginning of the game. Personally I want them to be disabled at the beginning so they can be enabled manually by the player later on. The reason I am struggling with this is because I am not the one who made the script, however, I have tried solving it but I did not succeed.
script.LazerGateLocalScript.LazerGate.Value = script.Parent -- setting a
value
local configs = script.Parent.Configurations
local lazers = script.Parent.LazerGate -- making it easier to access this
part
local lazersOn = true -- so we know if the lasers are on or off
for i, node in pairs(lazers:GetChildren()) do
for i, component in pairs(node:GetChildren()) do
if component.Name == "Emitter" then
local lazerBeam = component:FindFirstChild("ParticleEmitter")
local lazerColor = configs.LazerColor.Value
lazerBeam.Color = ColorSequence.new(lazerColor, lazerColor) -- Setting the lazer color to the lazer color found in the configurations of this model
elseif component.Name == "Diode" then
component.BrickColor = configs.DiodeColor.Value
local diodeSparkle = component:FindFirstChild("ParticleEmitter")
diodeSparkle.Color = ColorSequence.new(Color3.new(255,255,255), configs.DiodeSparkleColor.Value)
elseif component.Name == "Lense" then
component.BrickColor = configs.DiodeColor.Value
end
end
end
script.Parent.KillBrick.PointLight.Color = configs.LazerColor.Value
game.Players.PlayerAdded:connect(function(player) -- when a player is added
player.CharacterAdded:connect(function() -- and whenever their character is loaded then
local newScript = script.LazerGateLocalScript:Clone() -- clone the local script
newScript.Parent = player.PlayerGui -- and put it in the player's playerGui
end)
end)
function lazerToggle(OnOff) -- this funtionc simply changes whether the lasers are on or off
for i, node in pairs(lazers:GetChildren()) do
for i, component in pairs(node:GetChildren()) do
if component.Name == "Emitter" then
local lazerBeam = component:FindFirstChild("ParticleEmitter")
if OnOff == true then
lazerBeam.Enabled = true
else
lazerBeam.Enabled = false
end
end
end
end
end
script.Parent.KillBrick.Touched:connect(function(obj)
if obj.Parent and obj.Parent:FindFirstChild("Humanoid") and lazersOn == true then
obj.Parent:BreakJoints()
end
end)
script.Parent.LazerToggle.OnServerEvent:connect(function() -- when an event is fired then see if we are to open or close the lid and set a value to do so
if lazersOn == true then
lazerToggle(false)
wait(1.5)
lazersOn = false
else
lazerToggle(true)
wait(0.5)
lazersOn = true
end
end)
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
mouse.Button1Down:connect(function() -- if the player chicks then ...
if script.LazerGate.Value and mouse.Target.Name == "LazerButton" and mouse.Target.Parent.Name == "LazerGateSection" then -- if they click the laser gates button
script.LazerGate.Value.LazerToggle:FireServer() -- fire an event that the script will use
end
end)
Once again, my issue is that I want the lasers to be disabled, not enabled at the beginning. Any help would be greatly appreciated. Also, I am very aware that I will be receiving downvotes for this post (xD). But I'll really appreciate any help!
Thanks in advance,
E.W
From what the code tells me, this should work:
script.LazerGateLocalScript.LazerGate.Value = script.Parent
local configs = script.Parent.Configurations
local lazers = script.Parent.LazerGate
local lazersOn = false
for _, node in pairs(lazers:GetChildren()) do
for _, component in pairs(node:GetChildren()) do
if component.Name == "Emitter" then
local lazerBeam = component:FindFirstChild("ParticleEmitter")
local lazerColor = configs.LazerColor.Value
lazerBeam.Color = ColorSequence.new(lazerColor, lazerColor)
elseif component.Name == "Diode" then
component.BrickColor = configs.DiodeColor.Value
local diodeSparkle = component:FindFirstChild("ParticleEmitter")
diodeSparkle.Color = ColorSequence.new(Color3.new(255,255,255), configs.DiodeSparkleColor.Value)
elseif component.Name == "Lense" then
component.BrickColor = configs.DiodeColor.Value
end
end
end
script.Parent.KillBrick.PointLight.Color = configs.LazerColor.Value
game.Players.PlayerAdded:connect(function(player)
player.CharacterAdded:connect(function()
local newScript = script.LazerGateLocalScript:Clone()
newScript.Parent = player.PlayerGui
end)
end)
function lazerToggle(OnOff)
for _, node in pairs(lazers:GetChildren()) do
for _, component in pairs(node:GetChildren()) do
if component.Name == "Emitter" then
local lazerBeam = component:FindFirstChild("ParticleEmitter")
if OnOff then
lazerBeam.Enabled = true
else
lazerBeam.Enabled = false
end
end
end
end
end
script.Parent.KillBrick.Touched:connect(function(obj)
if obj.Parent and obj.Parent:FindFirstChild("Humanoid") and lazersOn == true then
obj.Parent:BreakJoints()
end
end)
script.Parent.LazerToggle.OnServerEvent:connect(function()
if lazersOn == true then
lazerToggle(false)
wait(1.5)
lazersOn = false
else
lazerToggle(true)
wait(0.5)
lazersOn = true
end
end)
lazerToggle(false);
The code above goes into the first script, the server side script which has a child called LazerGateLocalScript.
local player = game.Players.LocalPlayer
local mouse = player:GetMouse()
mouse.Button1Down:connect(function()
if script.LazerGate.Value and mouse.Target.Name == "LazerButton" and mouse.Target.Parent.Name == "LazerGateSection" then
script.LazerGate.Value.LazerToggle:FireServer()
end
end)
And then this code above goes into the local script which is a child of the server script called LazerGateLocalScript
Just if you ask, yes, I know RobloxLua.

Resources