Can someone please help me figure out why my gui bar changes size and position after the game starts?
-- LocalScript in StarterPlayerScripts
local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local hungerGui = player:WaitForChild("PlayerGui"):WaitForChild("HungerGui")
local hungerBar = hungerGui:WaitForChild("HungerBar")
local fillFrame = hungerBar:WaitForChild("Fill")
local maxHunger = 100
local currentHunger = maxHunger
local foodFolder = game.Workspace:WaitForChild("FoodFolder")
local eating = false
-- Customizable hunger decrease rate in seconds and decrease amount
local hungerDecreaseRate = 2 -- Decreases hunger every 2 seconds
local hungerDecreaseAmount = 1 -- Decrease hunger by 1 unit each time
-- Function to update the hunger bar UI
local function updateHungerBar()
fillFrame.Size = UDim2.new(currentHunger / maxHunger, 0, 1, 0)
end
-- Function to handle eating food
local function eatFood(food)
if eating then return end
eating = true
local hungerValue = food:FindFirstChild("HungerValue")
if hungerValue then
currentHunger = math.min(currentHunger + hungerValue.Value, maxHunger)
updateHungerBar()
-- Play eating sound
local sound = food:FindFirstChildOfClass("Sound")
if sound then
sound:Play()
end
-- Disable food and particles
food.Transparency = 1
food.CanCollide = false
for _, emitter in ipairs(food:GetChildren()) do
if emitter:IsA("ParticleEmitter") then
emitter.Enabled = false
end
end
-- Respawn food after 5 seconds
wait(5)
if food and food.Parent then
food.Transparency = 0
food.CanCollide = true
for _, emitter in ipairs(food:GetChildren()) do
if emitter:IsA("ParticleEmitter") then
emitter.Enabled = true
end
end
end
end
eating = false
end
-- Function to find the nearest food within a certain distance
local function findNearestFood()
local nearestFood = nil
local shortestDistance = math.huge
local rootPart = character:WaitForChild("HumanoidRootPart")
for _, food in ipairs(foodFolder:GetChildren()) do
if food:IsA("BasePart") and food.Transparency == 0 then
local distance = (food.Position - rootPart.Position).magnitude
if distance < shortestDistance and distance <= 5 then
shortestDistance = distance
nearestFood = food
end
end
end
return nearestFood
end
-- Function to handle key press for eating
local function onKeyPress(actionName, inputState, inputObject)
if inputState == Enum.UserInputState.Begin then
local food = findNearestFood()
if food then
eatFood(food)
end
end
end
-- Bind the "E" key to eat food
game.ContextActionService:BindAction("EatFood", onKeyPress, false, Enum.KeyCode.E)
-- Decrease hunger over time
spawn(function()
while true do
wait(hungerDecreaseRate)
currentHunger = currentHunger - hungerDecreaseAmount
if currentHunger <= 0 then
humanoid:TakeDamage(1)
end
updateHungerBar()
end
end)