Trying to index a Parent results in a nil value - lua

Error:
16:16:03.496 - Workspace.Storeroom.Pile of Crates.Wood Crate.Script:17: attempt to index field 'Parent' (a nil value)
Script:
local db = true
local clickdetector = script.Parent:WaitForChild('ClickDetector')
clickdetector.MouseClick:Connect(function(plr)
local randomizer = math.random(1,6)
if randomizer == 1 or 2 or 3 then
script.Parent:Destroy()
local gift = game:GetService("ReplicatedStorage"):WaitForChild("Blue Keycard")
if db == true then
db = false
gift:Clone().Parent = plr.Backpack
wait(1)
db = true
end
end
if randomizer == 4 or 5 then
script.Parent:Destroy()
local gift = game:GetService("ReplicatedStorage"):WaitForChild("Red Keycard")
if db == true then
db = false
gift:Clone().Parent = plr.Backpack
wait(1)
db = true
end
end
if randomizer == 6 then
script.Parent:Destroy()
local gift = game:GetService("ReplicatedStorage"):WaitForChild("Green Keycard")
if db == true then
db = false
gift:Clone().Parent = plr.Backpack
wait(1)
db = true
end
end
end)

if randomizer == 1 or 2 or 3 then
if randomizer == 4 or 3 then
These lines won't work as you think it should. It doesn't check if randomizer value is in some set of predefined values. Expression randomizer == 1 or 2 or 3 evaluates (depending on randomizer exact value) either to true or to 2, which is interpreted as true in if/then construct.
If you really want to check the value against the list, you should do something like:
local set1 = {1=true, 2=true, 3=true}
local set2 = {4=true, 5=true}
-- somewhere much later
if set1[randomizer] then .. end
Start with fixing this issue.

Related

Lua function constantly returning false out of SQL function

I have this code
function IsAuthorized(xPlayer, doorID, locked, usedLockpick)
local jobName, grade = {}, {}
jobName[1] = xPlayer.job.name
grade[1] = xPlayer.job.grade
if xPlayer.job2 then
jobName[2] = xPlayer.job2.name
grade[2] = xPlayer.job2.grade
end
local canOpen = false
if doorID.lockpick and usedLockpick then
count = xPlayer.getInventoryItem('lockpick').count
if count and count >= 1 then canOpen = true end
end
if not canOpen and doorID.authorizedJobs then
for job,rank in pairs(doorID.authorizedJobs) do
if (job == jobName[1] and rank <= grade[1]) or (jobName[2] and job == jobName[2] and rank <= grade[2]) then
canOpen = true
if canOpen then break end
end
end
end
if not canOpen and doorID.items then
local count
for k,v in pairs(doorID.items) do
count = xPlayer.getInventoryItem(v).count
if count and count >= 1 then
canOpen = true
local consumables = { ['ticket']=1 }
if locked and consumables[v] then
xPlayer.removeInventoryItem(v, 1)
end
break
end
end
if not count or count < 1 then canOpen = false end
end
if not canOpen then
local group = xPlayer.getGroup()
if group == 'management' or group == 'owner' then
print(group..' '..xPlayer.getName()..' was authorised to use a door')
canOpen = true
end
if doorID.authorizedgang then
print(xPlayer.identifier .. " | " .. doorID.authorizedgang)
MySQL.Async.fetchSingle('SELECT * FROM users WHERE identifier = ? AND gang = ?', {xPlayer.identifier, doorID.authorizedgang}, function(foundplayer)
if foundplayer then
print("found")
canOpen = true
print(canOpen)
end
----------------------------canopen returns true until here
end)
end
end
print(canOpen)
return canOpen
end
Essentially what is does is return a true or false value based on the if statements. I did not write this script myself, I simply added on. The code that I added to this function is
if doorID.authorizedgang then
print(xPlayer.identifier .. " | " .. doorID.authorizedgang)
MySQL.Async.fetchSingle('SELECT * FROM users WHERE identifier = ? AND gang = ?', {xPlayer.identifier, doorID.authorizedgang}, function(foundplayer)
if foundplayer then
print("found")
canOpen = true
print(canOpen)
end
----------------------------canopen returns true until here
end)
end
This code essentially makes a database call to check if it'll find a player with X identifier and Y gang, and this actually does work because it prints out "found" and canOpen returns true until the line that I marked, after this it returns false at the bottom of the function.
I've been trying other ways to get the data but ultimately I need the SQL DB call for this and im not sure why the variable isnt setting when in fact the database returns found. Any ideas what I could be doing wrong here?

Roblox Studio Problems with Coden the UI Elements, what need to to?

Good day,
i have the problem that i wana make my visit ui only visible when i am at spawn so at first i wanted to do it with checking the team but i dont found any solousion on how to check which player is in which and than disable/enable ui for them. So after this i made an bool inside of the ui named Loby and got it to work that it turns on / off based on where you are but the problem is that i dont get the ui working i tried this now for serveral hours but i just dont get it and i dont know why. Its only prints not in Loby else if im in Loby or in a round ;(, i hope someone can help me!, Good day
FyMa2618
local loby = script.Parent.Loby
while loby.Value == false do
print("Not In Lobby")
script.Parent.Enabled = false
wait(.1)
end
while loby.Value == true do
local ready = script.Parent.Loaded
print("Lobby is Active")
script.Parent.Enabled = true
wait(.1)
end
--its a local script in the same position as the Bool.
The round script(nedded for the bool)
local intermission = 25
local roundLength = 45
local inRound = game.ReplicatedStorage.InRound
local staus = game.ReplicatedStorage.Status
-- when round value is changed
inRound.Changed:Connect(function()
if inRound.Value == false then
for i, plr in pairs(game.Players:GetChildren()) do
local char = plr.Character
local humanRoot = char:WaitForChild("HumanoidRootPart")
humanRoot.CFrame = game.Workspace.lobbySpawn.CFrame
end
end
end)
-- changes the status
local function round()
while true do
inRound.Value = false
for i = intermission, 0, -1 do
staus.Value = "Game will start in "..i.." seconds"
wait(1)
end
inRound.Value = true
wait(3)
for i = roundLength, 0, -1 do
wait(1)
staus.Value = "Game will end in "..i.." seconds"
local playing = {}
for i, plr in pairs(game.Players:GetChildren()) do
if plr.Team.Name == "Playing" then
local b = game.StarterGui.SpectateGUI.Loby
b.Value = false
table.insert(playing, plr.Name)
print("inserted player")
end
end
if #playing == 0 then
staus.Value = "Everyone Has Died"
wait(3)
break
end
end
end
end
The Region 3 Code(also needed for the bool)
local RegionPart = game.Workspace.RegionPart
local pos1 = RegionPart.Position - (RegionPart.Size / 2)
local pos2 = RegionPart.Position + (RegionPart.Size / 2)
local region = Region3.new(pos1, pos2)
--[[
local part = Instance.new("Part")
part.Anchored = true
part.Size = region.Size
part.Parent = game.Workspace
part.CanCollide = false
part.Transparency = 0.4
dont worry about this
]]--
while true do
wait()
local partsInRegion = workspace:FindPartsInRegion3(region, nil, 1000)
for i, part in pairs(partsInRegion) do
if part.Parent:FindFirstChild("Humanoid") ~= nil then
local char = part.Parent
local loby = game.StarterGui.SpectateGUI.Loby
loby.Value = true
end
end
end[Starter UI][1]

Why does this Int Value keep coming back after it is set? [Roblox Studio]

I'm sorry if this is a really simple or easy question, but I am trying to set the player leaderstat "Money" to 0, but it keeps coming back as the old value. The only thing that I can think of that may be causing this problem is that the moneyGain script is on repeat.
Here is my moneyGain script:
local playerMoney
while wait(0.24) do
local buttons = script.Parent.Parent.info.savedItems.Value.buttons:GetChildren()
for button = 1, #buttons, 1 do
if buttons[button].Parent.Parent.tycoon.Value ~= nil then
if buttons[button].Parent.Parent.tycoon.Value.info.owner ~= nil then
if buttons[button].jobDone.Value == true then
script.Parent.moneyEnforcer.enforce:Invoke(buttons[button].gainVal.Value)
end
end
end
end
--OWNERDOOR:
if script.Parent.Parent.info.owner.Value ~= nil then
script.Parent.moneyEnforcer.enforce:Invoke(1)
end
end
Here is my moneyEnforcer script:
local rs = game:GetService("ReplicatedStorage")
local dictionary = require(rs.dictionary)
local vipPlayers = dictionary.vipPlayers
script.enforce.OnInvoke = function(amount)
print(amount)
if script.Parent.Parent.info.player.Value ~= nil then
if game:GetService("GamePassService"):PlayerHasPass(script.Parent.Parent.info.player.Value, 25494219) then
amount = amount * 2
else
for i = 1, #vipPlayers, 1 do
if script.Parent.Parent.info.player.Value.Name == vipPlayers[i] then
amount = amount * 2
end
end
end
local playerMoney = script.Parent.Parent.info.player.Value.leaderstats.Money
script.Parent.Parent.info.player.Value.leaderstats.Money.Value = script.Parent.Parent.info.player.Value.leaderstats.Money.Value + amount
end
end
And here is the tycoon reseter:
local player = script.Parent.Parent.Parent.Parent.Parent.Parent
script.Parent.Parent.Parent.Visible = false
script.Parent.MouseButton1Click:Connect(function()
player.leaderstats.Money.Value = 0
script.Parent.Parent.Parent.Visible = false
local savedItems = player.claimedTycoon.Value.info.savedItems.Value
local builds = player.claimedTycoon.Value.activeBuilds:GetChildren()
local buttons = player.claimedTycoon.Value.activeButtons:GetChildren()
for i = 1, #builds, 1 do
builds[i].Parent = savedItems.builds
end
for j = 1, #buttons, 1 do
buttons[j].Parent = savedItems.buttons
end
savedItems.builds.dirtStarterBase.Parent = player.claimedTycoon.Value
player.claimedTycoon.Value.info:WaitForChild("activeWave").Value = 1
end)
I have tried putting the "script.Parent.Parent.info.player.Value.leaderstats.Money.Value = script.Parent.Parent.info.player.Value.leaderstats.Money.Value + amount" on the moneyGain script, but that made no difference.
Any help is appriciated!
I believe your problem is that you're setting the value of money from the client. When you change the value from a local script, it will not update on the server. To fix this update the value from the server
In tycoon reseter, try resetting the value from the server using a RemoteEvent

Why does Roblox & Roblox Studio both crash when running certain scripts with no error code?

So here's the deal, I'm working on a game that is similar to a murder mystery and this part of the system is to start the round and show the players their roles and then the map. Except it used to work and I didn't knowingly do anything to the scripts that would affect it so the game crashes when this part is carried out. All I know is it starts to display the role and often does, it also plays the sound and displays the correct description, however it crashes just after that and sometimes just before the role is revealed. I've attached the function that runs when the RoundStarter event is fired to the client.
The server doesn't crash but, all of the clients do but not all at the exact same moment in time; Previously when there has been errors, I've been able to identify an error message but none of the clients throw any clear issues.
In testing mode in Roblox Studio, they freeze just after the drum roll sound effect as the role is displayed, however no errors and the server seems to be acting normally. Near enough the same thing happens when ran in Roblox.
Clientside script
ReplicatedStorage.Players.Events.RoundStarter.OnClientEvent:Connect(function(Role,Map)
local player = game.Players.LocalPlayer
player.CameraMode = Enum.CameraMode.LockFirstPerson
script.Parent.RoundGui.RoundEnd.Visible = false
game.Players.LocalPlayer.NameDisplayDistance = 0
CURRENTROLE = Role
CURRENTMAP = Map
script.Parent.RoundGui.Enabled = true
script.Parent.RoundGui.RoundStarter.Visible = true
script.Parent.RoundGui.RoundStarter.Fader.Visible = true
script.Parent.RoundGui.RoundStarter.Fader.BackgroundTransparency = 0
script.Parent.RoundGui.RoundStarter.RoleDescription.Visible = false
script.Parent.RoundGui.RoundStarter.RoleName.Visible = false
script.Parent.RoundGui.RoundStarter.Text.Visible = true
local transp = 0
for i = 1,50,1 do
transp += 0.05
script.Parent.RoundGui.RoundStarter.Fader.BackgroundTransparency = transp
wait(.1)
end
script.Parent.RoundGui.RoundStarter.DR:Play()
script.Parent.RoundGui.RoundStarter.RoleName.Visible = true
script.Parent.RoundGui.RoundStarter.RoleName.Text = Role
script.Parent.RoundGui.RoundStarter.RoleDescription.Visible = true
if Role == "Civilian" then
script.Parent.RoundGui.RoundStarter.RoleDescription.Text = "Your Job is to help the Inspector find the shadow... Work to figure them out and stop them before it's too late! Don't tell anyone your Role!"
script.Parent.RoundGui.RoundStarter.RoleName.TextColor3 = Color3.fromRGB(0, 255, 17)
elseif Role == "Shadow" then
script.Parent.RoundGui.RoundStarter.RoleName.TextColor3 = Color3.fromRGB(255, 0, 0)
script.Parent.RoundGui.RoundStarter.RoleDescription.Text = "It's time... Infiltrate the crowd, gain their trust and kill the inspector to win! By killing another player, You can take on their form and blend in with the Civilians. More help will be on left of the screen. Don't tell anyone your Role!"
elseif Role == "Inspector" then
script.Parent.RoundGui.RoundStarter.RoleName.TextColor3 = Color3.fromRGB(0, 38, 255)
script.Parent.RoundGui.RoundStarter.RoleDescription.Text = "You are nominated to fight the Shadow and eliminate them. You must work with the Civilians to figure out who the Shadow is, if you die you lose. Don't tell anyone your Role!"
end
wait(10)
script.Parent.RoundGui.RoundStarterMap.Visible = true
script.Parent.RoundGui.RoundStarterMap.Fader.Visible = true
script.Parent.RoundGui.RoundStarterMap.MapDescription.Visible = false
script.Parent.RoundGui.RoundStarterMap.MapName.Visible = false
local transp = 0
for i = 1,50,1 do
transp += 0.05
script.Parent.RoundGui.RoundStarterMap.Fader.BackgroundTransparency = transp
wait(.1)
end
script.Parent.RoundGui.RoundStarterMap.MapName.Visible = true
script.Parent.RoundGui.RoundStarterMap.MapName.Text = Map
script.Parent.RoundGui.RoundStarter.Dun:Play()
if Map == "The Office" then
script.Parent.RoundGui.RoundStarterMap.MapDescription.Text = "A classic map based in an Office building, in a power cut, near midnight. With an outdoor and Indoor area to explore, will you survive?"
elseif Map =="The Village" then
script.Parent.RoundGui.RoundStarterMap.MapDescription.Text = "The original map based in a small villiage with numerous buildings and areas to explore."
end
script.Parent.RoundGui.RoundStarterMap.MapDescription.Visible = true
wait(10)
script.Parent.RoundGui.RoundEnd.Visible = false
script.Parent.RoundGui.RoundStarterMap.Visible = false
script.Parent.RoundGui.RoundStarter.Visible = false
end)
--This is the next function in the code that should be executed at a similar time to the above one (It should have an InMap value of true.
ReplicatedStorage.Players:WaitForChild(player.Name).InMap.Changed:Connect(function()
data = game.ReplicatedStorage.GetPlayerDataCS:InvokeServer()
if ReplicatedStorage.Players[player.Name].InMap.Value == false then
--StartGUI:SetCoreGuiEnabled(Enum.CoreGuiType.PlayerList, true)
player.CameraMode = Enum.CameraMode.Classic
--StartGUI:SetCoreGuiEnabled(Enum.CoreGuiType.Chat,true)
script.Parent.LobbyGui.Enabled = true
script.Parent.RoundGui.Enabled = false
wait()
else
if CURRENTROLE == "Shadow" then
script.Parent.RoundGui.ShadowPanel.Visible = true
script.Parent.RoundGui.CivPanel.Visible = false
script.Parent.RoundGui.InsPanel.Visible = false
if data then
if data.EquippedAbility ~="None" and data.EquippedAbility ~="" then
script.Parent.RoundGui.ShadowPanel[data.EquippedAbility].Visible = true
end
end
elseif CURRENTROLE == "Inspector" then
script.Parent.RoundGui.ShadowPanel.Visible = false
script.Parent.RoundGui.CivPanel.Visible = false
script.Parent.RoundGui.InsPanel.Visible = true
else
script.Parent.RoundGui.ShadowPanel.Visible = false
script.Parent.RoundGui.CivPanel.Visible = true
script.Parent.RoundGui.InsPanel.Visible = false
end
--StartGUI:SetCoreGuiEnabled(Enum.CoreGuiType.PlayerList, false)
--StartGUI:SetCoreGuiEnabled(Enum.CoreGuiType.Chat,true)
script.Parent.LobbyGui.Enabled = false
script.Parent.RoundGui.Enabled = true
wait()
end
end)
Here's also the script on the server that should be near the event.
local replicatedstor = game:GetService("ReplicatedStorage")
local playersinthemap = {}
local playersinserver = game.Players:GetPlayers()
local maplist = {"The Village"}
local TESTINGMODE = false
local goodwin = false
local COUNT = 0
local deadpool = {}
local DataStoreService = game:GetService("DataStoreService")
local Datastore = DataStoreService:GetDataStore("THE_MASQUERADE_TEST2")
function UpdateStatuses(Playerr,NewStatus)
local c = Playerr
if NewStatus == "Lobby" or NewStatus == "AFK" then
if game.ReplicatedStorage.Players[c.Name].Status.Value == "Shadow" then
script.RoundsInProgress.Value = false
goodwin = true
elseif game.ReplicatedStorage.Players[c.Name].Status.Value == "Inspector" then
script.RoundsInProgress.Value = false
goodwin = false
end
game.ReplicatedStorage.Players[c.Name].InMap.Value = false
if table.find(playersinthemap,c,1)~= nil then
local index = table.find(playersinthemap,c,1)
table.remove(playersinthemap,index)
end
end
game.ReplicatedStorage.Players[c.Name].Status.Value = NewStatus
if #playersinthemap <= 2 and script.RoundsInProgress.Value == true then
script.RoundsInProgress.Value = false
goodwin = false
end
end
game.ReplicatedStorage.Players.Events.SetStatus.OnServerEvent:Connect(function(Player,Status)
if Status ~= nil then
UpdateStatuses(Player,Status)
else
print ("Tried to change status of Player but the given status was nil.")
end
end)
while true do
while script.RoundsRunning.Value == true do
game.ReplicatedStorage.Players.Events.Notify:FireAllClients("Intermission...","L",false)
--game.ReplicatedStorage.Game.Intermission:Fire(30)
--game.ReplicatedStorage.Game.Intermission.Event:Wait()
wait(35)
game.Workspace.Lobby.DATABOARD.SurfaceGui.Frame.Title.Text = "Round starting soon..."
--game.ReplicatedStorage.Players.Events.Notify:FireAllClients("Round starting soon...","L",true)
--game.Workspace.Lobby.DATABOARD.SurfaceGui.Frame.Time.Text = ""
if not game.Workspace.Map then
playersinthemap = {}
local Mapfolder = Instance.new("Folder",game.Workspace)
Mapfolder.Name = "Map"
end
playersinserver = game.Players:GetPlayers()
wait(10)
playersinserver = game.Players:GetPlayers()
if #playersinserver >= 4 or (TESTINGMODE == true and #playersinserver >= 3) then
game.Workspace.Lobby.DATABOARD.SurfaceGui.Frame.Title.Text = "Round loading..."
game.ReplicatedStorage.Players.Events.Notify:FireAllClients("Loading the round now...","L",false)
playersinserver = game.Players:GetPlayers()
local chosenMapIndex = math.random(#maplist)
local chosenMapName = maplist[chosenMapIndex]
local chosenShadowIndex = math.random(#playersinserver)
local chosenShadow = playersinserver[chosenShadowIndex]
local chosenInspectorIndex = math.random(#playersinserver)
local chosenInspector = playersinserver[chosenInspectorIndex]
while chosenInspector == chosenShadow do
chosenInspectorIndex = math.random(#playersinserver)
chosenInspector = playersinserver[chosenInspectorIndex]
end
local playernumber = playersinserver
COUNT = 0
while COUNT ~= #playersinserver do
COUNT += 1
local playername = playersinserver[COUNT].Name
print (playersinserver)
print ("Player trying to send role data:"..playername)
if playersinserver[COUNT] == chosenShadow then
game.ReplicatedStorage.Players.Events.RoundStarter:FireClient(playersinserver[COUNT],"Shadow",chosenMapName)
game.ReplicatedStorage.Players[playersinserver[COUNT].Name].Status.Value = "Shadow"
--temp = game.ReplicatedStorage.ReadStatus:Invoke(playername,"Shadow")
elseif playersinserver[COUNT] == chosenInspector then
game.ReplicatedStorage.Players.Events.RoundStarter:FireClient(playersinserver[COUNT],"Inspector",chosenMapName)
game.ReplicatedStorage.Players[playersinserver[COUNT].Name].Status.Value = "Inspector"
--temp = game.ReplicatedStorage.ReadStatus:Invoke(playername,"Inspector")
else
game.ReplicatedStorage.Players.Events.RoundStarter:FireClient(playersinserver[COUNT],"Civilian",chosenMapName)
game.ReplicatedStorage.Players[playersinserver[COUNT].Name].Status.Value = "Civilian"
--temp = game.ReplicatedStorage.ReadStatus:Invoke(playername,"Civilian")
end
end
wait()
local MapInServerStorage = game.ServerStorage.Maps:FindFirstChild(chosenMapName)
local LoadedMap = MapInServerStorage:Clone()
LoadedMap.Parent = game.Workspace.Map
local spawns = {}
for i,c in pairs(LoadedMap:GetDescendants()) do
if c.Name == "Spawn" then
table.insert(spawns,1,c)
end
end
COUNT = 0
local i = COUNT
while COUNT ~= #playersinserver do
COUNT += 1
print ("Setting Character locations. Loop:"..COUNT)
local spawnlistindex = math.random(#spawns)
playersinserver[COUNT].Character:SetPrimaryPartCFrame(spawns[spawnlistindex].CFrame)
--playersinserver[COUNT].Character:SetPrimaryPartCFrame(LoadedMap.Spawns.Spawn.CFrame)
table.insert(playersinthemap,1,playersinserver[COUNT])
playersinserver[COUNT].NameDisplayDistance = 0
game.ReplicatedStorage.Players:FindFirstChild(playersinserver[COUNT].Name).InMap.Value = true
if playersinserver[COUNT] == chosenInspector then
local data = game.ReplicatedStorage.GetPlayerData:Invoke(chosenInspector)
Pistl = game.ServerStorage.Guns[data.EquippedSkin]:Clone()
Pistl.Parent = playersinserver[COUNT].Backpack
end
end
print ("Round starting...")
--This is then followed by the rest of the round system which should be working but I have cut it to try to shorten the amount of reading but can be supplied if needed. It is closed correctly.
I've tried to keep the code to a minimum however it could be anywhere and as there are no obvious script related error codes, I'm requesting some assistance in some way.
There are other things that may have caused it but this is becoming a real issue, especially since it used to work, and I've included all of the likely suspects but I'm happy to give anything else if these aren't incorrect in anyway.
If you wish to see what happens yourself, you'll need either 4 Roblox Accounts or 3 extra friends.
Here's the game on Roblox: The Masquerade
If anything else is needed, feel free to let me know and thanks for reading and any potential help. (Just so you know, I have done a lot of research on all of the functions and things I'm using but I can't find any issues, it just freezes & crashes).
The only error codes I've got are:
Start Process Exception...
Uploading crash analytics
Done uploading crash analytics
There are some random wait() statements without any arguments, which shouldn't be in your code anyway. This may very well hang up the server / client.
Also, you appear to have a few while loops which do not have any wait()'s. That's a pretty common problem which stalls the client executing the script. Try adding at least
wait(0.01) to the end of each while true loop that doesn't have it already.
There might be some occurences of this in the client as well (like that one lonely wait() with no parameters), but here's a modified version of your server script:
while true do
while script.RoundsRunning.Value == true do
game.ReplicatedStorage.Players.Events.Notify:FireAllClients("Intermission...","L",false)
--game.ReplicatedStorage.Game.Intermission:Fire(30)
--game.ReplicatedStorage.Game.Intermission.Event:Wait()
wait(35)
game.Workspace.Lobby.DATABOARD.SurfaceGui.Frame.Title.Text = "Round starting soon..."
--game.ReplicatedStorage.Players.Events.Notify:FireAllClients("Round starting soon...","L",true)
--game.Workspace.Lobby.DATABOARD.SurfaceGui.Frame.Time.Text = ""
if not game.Workspace.Map then
playersinthemap = {}
local Mapfolder = Instance.new("Folder",game.Workspace)
Mapfolder.Name = "Map"
end
playersinserver = game.Players:GetPlayers()
wait(10)
playersinserver = game.Players:GetPlayers()
if #playersinserver >= 4 or (TESTINGMODE == true and #playersinserver >= 3) then
game.Workspace.Lobby.DATABOARD.SurfaceGui.Frame.Title.Text = "Round loading..."
game.ReplicatedStorage.Players.Events.Notify:FireAllClients("Loading the round now...","L",false)
playersinserver = game.Players:GetPlayers()
local chosenMapIndex = math.random(#maplist)
local chosenMapName = maplist[chosenMapIndex]
local chosenShadowIndex = math.random(#playersinserver)
local chosenShadow = playersinserver[chosenShadowIndex]
local chosenInspectorIndex = math.random(#playersinserver)
local chosenInspector = playersinserver[chosenInspectorIndex]
while chosenInspector == chosenShadow do
chosenInspectorIndex = math.random(#playersinserver)
chosenInspector = playersinserver[chosenInspectorIndex]
end
local playernumber = playersinserver
COUNT = 0
while COUNT ~= #playersinserver do
COUNT += 1
local playername = playersinserver[COUNT].Name
print (playersinserver)
print ("Player trying to send role data:"..playername)
if playersinserver[COUNT] == chosenShadow then
game.ReplicatedStorage.Players.Events.RoundStarter:FireClient(playersinserver[COUNT],"Shadow",chosenMapName)
game.ReplicatedStorage.Players[playersinserver[COUNT].Name].Status.Value = "Shadow"
--temp = game.ReplicatedStorage.ReadStatus:Invoke(playername,"Shadow")
elseif playersinserver[COUNT] == chosenInspector then
game.ReplicatedStorage.Players.Events.RoundStarter:FireClient(playersinserver[COUNT],"Inspector",chosenMapName)
game.ReplicatedStorage.Players[playersinserver[COUNT].Name].Status.Value = "Inspector"
--temp = game.ReplicatedStorage.ReadStatus:Invoke(playername,"Inspector")
else
game.ReplicatedStorage.Players.Events.RoundStarter:FireClient(playersinserver[COUNT],"Civilian",chosenMapName)
game.ReplicatedStorage.Players[playersinserver[COUNT].Name].Status.Value = "Civilian"
--temp = game.ReplicatedStorage.ReadStatus:Invoke(playername,"Civilian")
end
end
-- wait() useless wait
local MapInServerStorage = game.ServerStorage.Maps:FindFirstChild(chosenMapName)
local LoadedMap = MapInServerStorage:Clone()
LoadedMap.Parent = game.Workspace.Map
local spawns = {}
for i,c in pairs(LoadedMap:GetDescendants()) do
if c.Name == "Spawn" then
table.insert(spawns,1,c)
end
end
COUNT = 0
local i = COUNT
while COUNT ~= #playersinserver do
COUNT += 1
print ("Setting Character locations. Loop:"..COUNT)
local spawnlistindex = math.random(#spawns)
playersinserver[COUNT].Character:SetPrimaryPartCFrame(spawns[spawnlistindex].CFrame)
--playersinserver[COUNT].Character:SetPrimaryPartCFrame(LoadedMap.Spawns.Spawn.CFrame)
table.insert(playersinthemap,1,playersinserver[COUNT])
playersinserver[COUNT].NameDisplayDistance = 0
game.ReplicatedStorage.Players:FindFirstChild(playersinserver[COUNT].Name).InMap.Value = true
if playersinserver[COUNT] == chosenInspector then
local data = game.ReplicatedStorage.GetPlayerData:Invoke(chosenInspector)
Pistl = game.ServerStorage.Guns[data.EquippedSkin]:Clone()
Pistl.Parent = playersinserver[COUNT].Backpack
end
wait(0.01)
end
wait(0.01)
end
These are just the rough steps, so implant the changes in your code the way you want them to be.

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.

Resources