Random Fish from Module Table

local FishMod = {}

FishMod.Fishes = {
	
	Dory = {
		name = "Dory",
		price = 50,
		islandname = "Starter"
	},
	Nemo = {
		name = "Neon",
		price = 50,
		islandname = "Starter"
	}
}

function FishMod:GetFish(hit)
	for _, fisch in pairs(FishMod.Fishes) do
		if hit.island.Value == fisch.islandname then
			
			print(hit.island.Value)
			return fisch
		end
	end
	
end

return FishMod

I needed help making the code choose between Dory and Nemo. Everything works completely fine so far just needed help making the script chose randomly between Dory and Nemo. These are the two fishes on the starter island as everything works completely fine so far.

Lets use math.random() to get a random number by 1 to max fishes the player can get in the table. Like: math.random(1,#table) this returns a number starting from 1, to total values in the table.

We make a new table and store all the specific island fishes in it so we only get those as a random fish. The fish are number in the table and we get them by the random number. Like: fishTable[1]

In the end we get.

function FishMod:GetFish(hit)
	local fishTable = {} -- new table for just [islandname] fishes
	for _, fisch in pairs(FishMod.Fishes) do
		if hit.island.Value == fisch.islandname then
			table.insert(fishTable,fisch) -- add to the table (this way makes them numbered)
			print(fisch.name)
			print(hit.island.Value)
		end
	end
	local randomFish = fishTable[math.random(1, #fishTable)] -- random fish
	return randomFish
end

I hope this helps and Have a Blessed Day! :smiley:

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.