When spawning an object using World.SpawnAsset.... 1) how does it know which asset is associated with which player if there are multiple players? Is there a check for this and then my real question is 2) how do you remove a spawned asset for a player when they leave the match? and then 3) How do I move the remaining items so they look nice? This one is maybe not as important as I could maybe just spawn a "player left" type asset.
This is to show all players health in a health bar and their name in a static UI location on screen the whole game. I could not find anything like that in community content. I have it working but when a player leaves it can get funky.
Here is my script...
local propBlueProgressBar = script:GetCustomProperty("blueProgressBar")
local propThePlayersName = script:GetCustomProperty("thePlayersName")
local panel = script.parent
function placeHealthBarsOnce()
-- get all the players in the game
local allPlayers = Game.GetPlayers()
for i, player in ipairs(allPlayers) do
if player == Game.GetLocalPlayer() then
-- don't show the local player but show the others
-- UI.PrintToScreen(player.name, Color.GREEN)
else
-- spawn the health bar in the panel heirarchy
playerHealthBar = World.SpawnAsset(propBlueProgressBar, {parent = panel})
playerNameBar = World.SpawnAsset(propThePlayersName, {parent = panel})
-- move the health bar down by 50 units... I think
playerHealthBar.y = i*50
playerNameBar.y = i*47.5
-- multiply player hit points so that it is 0.01 - 1 and can set the progress bar
playerHealthBar.progress = (player.hitPoints*0.01)
playerNameBar.text = player.name
-- the tick function is resetting the progress bar every tick to match up with the player health
function Tick()
for i, player in ipairs(allPlayers) do
-- multiply player hit points so that it is 0.01 - 1 and can set the progress bar
playerHealthBar.progress = (player.hitPoints*0.01)
end
end
end
end
end
Task.Wait(10)
placeHealthBarsOnce()
I get the following error when player leaves the game....
[BOT_Bot2][2021.01.16-09.30.04]Error running Lua task: [F6F652A1FCAED2CA] Game GetLocalPlayer API Example:30: Attempted to access an object that has been destroyed. Consider using Object.IsValid(myObject) to check for this condition.
[BOT_Bot2][2021.01.16-09.30.04]Tick function has stopped running. Script: "Game GetLocalPlayer API Example", Asset ID: F6F652A1FCAED2CA
I tried messing with tis Object.isValid but am clearly missing something or doing it incorrectly. I have used some of the code that Slinkous mentions in one the latest VODs where she was making a voting system similar to Among Us. I just grabbed what I needed as a start.
Help appreciated at always! Thanks so much. Also, let me know how I can help you either here or in Discord. I want to give back and help out. I will definitely get this released on Core Content once it is working well.