Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How would I change the image of an image label based on your health?

Asked by 7 years ago

This is what I've tried so far, however it gives me this error when I run it:

15:16:27.182 - Players.Player1.PlayerGui.ScreenGui.Frame.LocalScript:29: attempt to index field 'Image' (a string value) 15:16:27.183 - Stack Begin 15:16:27.184 - Script 'Players.Player1.PlayerGui.ScreenGui.Frame.LocalScript', Line 29 15:16:27.185 - Stack End

wait()
print("health")

local player = game.Players.LocalPlayer
local character = player.Character
local humanoid = character.Humanoid

local health = script.Parent.Health
local overlay = script.Parent.Overlay
local healthCounter = script.Parent.HealthText

game:GetService("RunService").Stepped:Connect(function()
    local healthPoints = humanoid.Health/humanoid.MaxHealth
        if healthPoints > 90 then
            overlay.Image = "https://roblox.com/asset/id=714844375"
        elseif healthPoints <= 90 then
            overlay.Image.Image = "https://roblox.com/asset/id=716007653"
        end
        healthCounter.Text = math.floor(humanoid.Health)
end)

1 answer

Log in to vote
0
Answered by 7 years ago
Edited 7 years ago

The error is on line 17 which you have overlay.Image.Image which need to just be Image, secondly using Stepped for this task is overkill and there are is a better available for us to use which is HealthChanged as we only should be updating the label when the health changes.

Example:-

-- we should get the player correctly
local player = game:GetService('Players').LocalPlayer
local char = player.Character or player.CharacterAdded:Wait() --get the players character or wit till they spawn which then passes the player model back
local humanoid = char:WaitForChild('Humanoid') -- wait for the humanoid

-- gui items
local overlay = script.Parent:WaitForChild('Overlay')
local healthCounter = script.Parent:WaitForChild('HealthText')

humanoid.HealthChanged:Connect(function(newHp) -- passes the new hp
    if newHp > 90 then
        overlay.Image = "https://roblox.com/asset/id=714844375"
    else -- as we only have two images we either set the first image else the second we do not need to check it as it can only be lower than or equal to 90
        overlay.Image= "https://roblox.com/asset/id=716007653"
    end
    healthCounter.Text = math.floor(newHp)

end)

I hope this helps, please comment if you do not understand how / why this code works.

Ad

Answer this question