Cannot end a While Do loop. I need help

I’m trying to make a script that can change players’ spawn location. And it loops after a few certain time.

I typed the script like this:

local Player = game.Players:GetPlayers()
local bob = true

game.Loaded:Connect(function()
   while bob == true do
       wait(1)
       local SpawnPoint = Player.RespawnLocation
       SpawnPoint = game.Workspace:FindFirstChild("w")
       wait(1)
       SpawnPont = game.Workspace:FindFirstChild("A")
   end
end)

But when I begin to try out the script in the wild, the respawn location didn’t change.

I couldn’t do anything since the output didn’t say any error message.

I need help since I don’t know where did I do wrong.

ice_screenshot_20200122-192355

Your second “SpawnPoint” is spelled incorrectly, it says SpawnPont.

Also you never change the player’s respawn location to the w spawn because you change it to A every time before setting it.

There are a few different issues with your script. Let’s go through each of them.


local Player = game.Players:GetPlayers()

Firstly, GetPlayers returns a list of players. Therefore, when you define Player, you’re defining it as a list of all players currently in the game. If you want to do this for each player, you’ll need to setup a function that runs when a new player joins your game.


game.Loaded:Connect(function()
    ...
end)

Secondly, you don’t need to wait for the game to load to start running your script. Since your script is running on the server, the game will have already loaded.


local bob = true

while bob == true do
    ...
end

There’s two points to make here.

  • bob == true will evaluate to true when bob is true. In other words, you don’t need to perform a comparison, you can just do: while bob do.
  • You don’t need to define a variable for bob, you can use the word true directly. while true do.

SpawnPoint = ...

When you assign a value to SpawnPoint, you are assigning it to a variable in your code and not to the player. Instead, you should be assigning the value to Player.RespawnLocation directly.


Taking all the above into account, your code should look like this.

local spawnA = workspace.A
local spawnW = workspace.w

local function playerAdded(player)
    player.RespawnLocation = spawnA
    while true do
        wait(1)
        if player.RespawnLocation== spawnA then
            player.RespawnLocation = spawnW
        else
            player.RespawnLocation = spawnA
        end
    end
end

game.Players.PlayerAdded:Connect(playerAdded)

I’m sure others can leave additional comments on why my code works, and how it could be improved. I’ve tried to leave it as simple as I can so you can see what I’ve done.

5 Likes

Isn’t it RespawnLocation? And capitalisation of player is inconsistent. Just minor typos

1 Like

Thank you so much, man. I’m kind of a rookie at this whole Lua thing. I only understand a few basic stuffs like if then, functions, Services, etc. Thanks!