I’m not sure if the title matches the topic. I don’t really know what name I should give this problem. I’m currently working on adding pets to my game, but I ran into a little issue that I don’t know how to fix. Whenever I click on a pet in my inventory, it should say if it’s equipped or not. The problem is that it only says “Unequip Pet” on the last pet that I equipped, it doesn’t say it on the pets before that.
for i, v in pairs(scrollingframe:GetDescendants()) do
if v.Name == "NewSelect" then
if v.Text == "1" then
local player = game.Players.LocalPlayer
for i2, v2 in pairs(player.Character.Pets:GetDescendants()) do
if v2:IsA("StringValue") then
local selectedPetUUID = v.Parent.UUID.Value
local equippedPetUUIDS = v2.Value
print(equippedPetUUIDS)
if selectedPetUUID ~= equippedPetUUIDS then
PetInfo.EquipPet.Text = "Equip Pet"
else
PetInfo.EquipPet.Text = "Unequip Pet"
end
end
end
end
end
end
I’m guessing this is because of the order of the pets. I put a print inside the script, and this is the result:
The second value is the value of the second pet that I equipped.
How would I fix this problem?
for i, v in ipairs(scrollingframe:GetDescendants()) do
if v.Name ~= "NewSelect" or v.Text ~= "1" then
continue
end
local player = game.Players.LocalPlayer
for i2, v2 in ipairs(player.Character.Pets:GetDescendants()) do
if v2:IsA("StringValue") then
local selectedPetUUID = v.Parent.UUID.Value
local equippedPetUUIDS = v2.Value
print(equippedPetUUIDS)
if selectedPetUUID == equippedPetUUIDS then
PetInfo.EquipPet.Text = "Unequip Pet"
break
else
PetInfo.EquipPet.Text = "Equip Pet"
end
end
end
end
I just changed that because ipairs is canonically supposed to be used for arrays like :GetDescendants(). That wasn’t the fix though, I just changed it because it would perform slightly better.
The break I added was the fix. It stops the loop when it is called. Your problem was that when the correct pet was labelled, it would change the text to “Unequip Pet” but then when it looped into another unequipped pet, it would change back to “Equip Pet” when it should’ve stayed at “Unequip Pet”. Break prevents this from happening by stopping the loop when you change the text to “Unequip Pet”.
Sorry if my explanation was confusing, it’s hard to explain this for me.
No problem, here’s an explanation of break in code form if you need it:
for i = 1, 100 do
--//Prints the value
print(i)
--//Checks if value is 55, then stops the loop
if i == 55 then
break
end
end
--//Last number it prints should be 55