I'm trying to make a small game by myself and I can't seem to do this part of the code without it giving an error. The error is ServerScriptService.MainScript:18: attempt to index global 'gui' (a nil value). I have the gui in the right place, and it works in solo mode. But in-game and when I run a server in studio with 2 players, it gives this error. I'm currently using this code. I even define what "gui" is. Help?
--Coded by BoostedUp local maps = game.ServerStorage:WaitForChild("Maps") local timebomb = game.ServerStorage:WaitForChild("TimeBomb") function locategui() for i, player in pairs(game.Players:GetPlayers()) do gui = player.PlayerGui.MainGui.MainFrame:WaitForChild("MainText") end end while wait(1) do locategui() if game.Players.NumPlayers >= 2 then gui.Text = "Welcome to Time Bomb!" elseif game.Players.NumPlayers < 2 then gui.Text = "Need 2 or more players to start!" end end
I think you're doing it wrong. What you wanna do is display the text to all of the GUIs, yet you only apply it to one of them ( the last one selected by the for function line 07 )
What you wanna do is apply the text to each of the GUIs, in order to do that, you would use this
while wait(1) do for i, player in pairs(game.Players:GetChildren()) do gui = player.PlayerGui.MainGui.MainFrame:WaitForChild("MainText") if game.Players.NumPlayers >= 2 then gui.Text = "Welcome to Time Bomb!" elseif game.Players.NumPlayers < 2 then gui.Text = "Need 2 or more players to start!" end end end
This will apply the text to each player.
Note: I think ":GetPlayers()" is not a correct method in a "for" function since it returns a table, gotta check that out.
The problem lies in the fact that you started off by changing the variable "gui" for each player in the game. You need to change locategui() so that it is inside of the while wait(1) do so that it can detect every player's gui. I did this below. You will need to customize it a bit more to suit your gametype, as "while wait(1) do" will have that line of code running every second.
--Coded by BoostedUp w/ edits by Uglypoe local maps = game.ServerStorage:WaitForChild("Maps") local timebomb = game.ServerStorage:WaitForChild("TimeBomb") while wait(1) do local text = nil if game.Players.NumPlayers >= 2 then text = "Welcome to Time Bomb!" else text = "Need 2 or more players to start!" end for _, player in pairs(game.Players:GetChildren()) do player.PlayerGui:WaitForChild("MainGui"):WaitForChild("MainFrame"):WaitForChild("MainText").Text = text end