Help With Making a Random Fish System

So I am working on a fishing game and I was trying to make the fishing rod catch a random fish from a dictionary. Here’s how the dictionary is set up:

local Example = {
	["Green Fish"] = "assetID",
	["Blue Fish"] = "assetID",
	["Red Fish"] = "assetID"
}

Basically, when a random fish from this table is chosen, the name is placed onto a GUI and the assetID is entered into an ImageLabel so it shows that image of the fish. I have been trying to make a randomizer do this, but since both values are strings, I can’t use the # operator from the table and it makes everything very confusing for me. All I need is someone to give me pointers in the right direction on making a randomizer that gives a string index and places the string value in a separate variable.

I have seen egg hatching tutorials that place the image in a folder and bring it out when a variable is chosen, which is a possible solution to my problem but I would prefer if I only had to put the image id of a fish in the table.

local Example = {
    {"Green Fish", "assetID"},
    {"Blue Fish", "assetID"},
    {"Red Fish", "assetID"}
}

local FishTable = Example[math.random(1, #Example)]
local Fish = FishTable[1]
local FishId = FishTable[2]
print(Fish, FishId)

I guess you could go the easier route and do this
or if you still want it to be a dictionary

local Example = {
    ["Green Fish"] = "assetID",
    ["Blue Fish"] = "assetID",
    ["Red Fish"] = "assetID"
}

function GetRandomFish(Table)
    local Count = 0
    local Number = 0

    for i, v in pairs(Table) do
        Count += 1
    end

    Number = math.random(1, Count)

    for i, v in pairs(Table) do
        if Count == Number then
            return i, v
        else
            Count -= 1
        end
    end
end

local Fish, FishId = GetRandomFish(Example)
print(Fish, FishId)

the second code block I gave for the dictionary could be improved to be more random, but it works

2 Likes

Your first code was just what I was looking for! I have learnt something thanks to this experience. :smile:

1 Like