Weather Table Chance

Hello! I am currently tying to create a simple weather system for my game. I got it to pick a random weather every morning, and then change corresponding to that selected weather. However, I wanted to make it so that it wasn’t just completely random. I was hoping to have it so there was higher chance to be clear, and only like a 30% chance it would rain and 10% chance it would storm. That way there would be more variety and be more realistic. That being said, I really don’t know how to work with chances in a table, my original table was just consisting of string values. Below is the image of what my table looked like before, and then what it looked like after watching a few tutorials. I honestly can’t figure it out and the tutorials aren’t working how I was hoping. If someone could just help me out or point me in the right direction that would be great! I am fairly new to scripting, so I just don’t know how to make this work correctly and effectively. As you can see in one of the images below, right now it just selects a random weather from the table with no weighted values. Thanks for reading! :slight_smile:

3Script
2script
Weather

3 Likes

One thing you can try is:

local WeatherNumber = math.random(1, 100)

if WeatherNumber >= 1 and WeatherNumber <= 30 then
    WeatherPicked = "Rain"
elseif WeatherNumber >= 31 and WeatherNumber <= 90 then
    WeatherPicked = "Clear"
elseif WeatherNumber >= 91 and WeatherNumber <= 100 then
    WeatherPicked = "Storm"
end

You can change and manipulate the scripts in many ways to make it more efficient.
Hope that helped.

2 Likes
local Weather = {
	{
		WeatherType = "Rain",
		Chance = 30
	},
	
	{
		WeatherType = "Storm",
		Chance = 10
	}
}

local function GetChance(Loot: table): any
	local Result = 0
	
	for _, Inner in Loot do
		Result += Inner.Chance
	end
	
	-- 1 is min chance -> 1% to 100%
	local ShakeChance = math.random(1, Result)
	
	for _, Inner in Loot do
		if ShakeChance <= Inner.Chance then
			return Inner.WeatherType
		else
			ShakeChance -= Inner.Chance
		end
	end
end
2 Likes

What does this do, I am not entirely sure how to get this to work.

This is simply an indication of the type of element; for example, only a table needs to be entered into this function, but it can return anything.

This is the exact same function, so to run it, type:

GetChance(Weather) -- Weather is your table that stores the chance and name of the weather.

Also rename Chance1, Chance2, Chance3 to Chance.

image

Alright, so I made the changes, but how do I get the result from the function?


Weather3

instead of

GetChance(Weather)

use

local WeatherPicked = GetChance(Weather)

Thank you so much bro, everything works perfectly. I appreciate it, have a great day!

1 Like

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