When the player first joins the game, they will be randomized a team and assigned it. However, yes, the team data works but the assigning itself isn’t working. Here’s my code:
local Teams = game:GetService("Teams")
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local islandDataStore = DataStoreService:GetDataStore("Test13")
local islands = Teams:GetTeams()
local function getRandomIsland()
local randomIndex = math.random(1, #islands)
local randomIsland = islands[randomIndex]
print("Randomly selected island: "..randomIsland.Name)
return randomIsland.Name
end
local function getPlayerIsland(player)
local success, previousIsland = pcall(function()
local island = islandDataStore:GetAsync(player.UserId)
-- Check if the retrieved island exists in the list of islands
if table.find(islands, island) then
return island
else
return nil
end
end)
if success and previousIsland then
return previousIsland
else
print("Player "..player.Name.." hasn't played before")
return nil
end
end
local function assignPlayerToIslandTeam(player, island)
local team = Teams:FindFirstChild(island)
if team then
print("Assigning "..player.Name.." to "..team.Name.." team")
player.Team = team
print(player.Name.." assigned to "..island.." team")
else
warn("Island team not found for "..island)
print("Available teams:")
for _, team in ipairs(islands) do
print(team.Name)
end
end
end
Players.PlayerAdded:Connect(function(player)
local island = getPlayerIsland(player)
if island then
print(player.Name.." previously assigned to "..island.." team")
assignPlayerToIslandTeam(player, island)
else
print("Island team not found for "..player.Name..", assigning a new random island")
island = getRandomIsland()
assignPlayerToIslandTeam(player, island)
islandDataStore:SetAsync(player.UserId, island)
print(player.Name.." assigned to "..island.." team and data saved")
end
end)
Players.PlayerRemoving:Connect(function(player)
local island = getPlayerIsland(player)
if island then
local success, _ = pcall(function()
islandDataStore:SetAsync(player.UserId, island)
end)
if success then
print(player.Name.." island data saved: "..island)
else
warn("Failed to save island data for "..player.Name)
end
end
end)