Home Entrance Everyone Wiki Search Login Register

Welcome, Guest. Please login or register. - Thinking of joining the forum??
June 15, 2024 - @392.86 (what is this?)
Forum activity rating: Three Star Posts: 42/1k.beats Unread Topics | Unread Replies | Own Posts | Own Topics | Random Topic | Recent Posts
News: :happy: Open the all windows! Your mind needs storms and air! :happy:

+  MelonLand Forum
|-+  World Wild Web
| |-+  ✁ ∙ Web Crafting
| | |-+  ☔︎ ∙ I need Help!
| | | |-+  HELP: Unity/C# Random Weather Script


« previous next »
Pages: [1] Print
Author Topic: HELP: Unity/C# Random Weather Script  (Read 1140 times)
cinni
Full Member ⚓︎
***


believe in your dreams <3

SpaceHey: Friend Me!
StatusCafe: cinni

View Profile WWW

First 1000 Members!OG! Joined 2021!
« on: May 17, 2022 @769.81 »

hello meloners,

maybe someone can help me out with a script i made :X i wanted to create randomized weather and i'm using this day & night script (below) as a starting point to determine when a day has gone by. I want it to rain on a random day, but right now it just rains every other day. I wasn't able to figure out how to successfully randomize it on my own, so if anyone could chime in i would appreciate it !! :4u:

my weather script:
Code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Weather : MonoBehaviour
{
  public GameObject particles;
  public DayAndNightControl time;
  int currentDay = 0;
  public int chanceRain;
  public int date;
  public int randomWeather;
  [Range(0, 1)]
  public float timeFloat;

  private void Update()
  {
    time = GameObject.FindObjectOfType<:grin:ayAndNightControl>();
    timeFloat = time.currentTime;
    date = time.currentDay;
    Debug.Log("the day is" + date);

    int chanceRain = Random.Range(1, 2);
    randomWeather = chanceRain * date;

    if (randomWeather%2==1)
    {
      particles.SetActive(true);
    }

    if (randomWeather%2==0)
    {
      particles.SetActive(false);
    }
  }
}


day & night script:
Code
//2016 Spyblood Games

using UnityEngine;
using System.Collections;

[System.Serializable]
public class DayColors
{
	public Color skyColor;
	public Color equatorColor;
	public Color horizonColor;
}

public class DayAndNightControl : MonoBehaviour {
	public bool StartDay; //start game as day time
	public GameObject StarDome;
  public GameObject NightDome;
	public GameObject moonState;
	public GameObject moon;
	public DayColors dawnColors;
	public DayColors dayColors;
	public DayColors nightColors;
	public int currentDay = 0; //day 8287... still stuck in this grass prison... no esacape... no freedom...
	public Light directionalLight; //the directional light in the scene we're going to work with
	public float SecondsInAFullDay = 120f; //in realtime, this is about two minutes by default. (every 1 minute/60 seconds is day in game)
	[Range(0,1)]
	public float currentTime = 0; //at default when you press play, it will be nightTime. (0 = night, 1 = day)
	[HideInInspector]
	public float timeMultiplier = 1f; //how fast the day goes by regardless of the secondsInAFullDay var. lower values will make the days go by longer
, while higher values make it go faster. This may be useful if you're siumulating seasons where daylight and night times are altered.
	public bool showUI;
	float lightIntensity; //static variable to see what the current light's insensity is in the inspector
	Material starMat;
  Material nightMat;

  float timeLeft;
  Color targetColor;

	Camera targetCam;

	// Use this for initialization
	void Start () {
		RenderSettings.ambientMode = UnityEngine.Rendering.AmbientMode.Trilight;
		foreach (Camera c in GameObject.FindObjectsOfType<Camera>())
		{
			if (c.isActiveAndEnabled) {
				targetCam = c;
			}
		}
		lightIntensity = directionalLight.intensity; //what's the current intensity of the light
		starMat = StarDome.GetComponentInChildren<MeshRenderer> ().material;
		if (StartDay) {
			currentTime = 0.3f; //start at morning
			starMat.color = new Color(1f,1f,1f,0f);
		}
    nightMat = NightDome.GetComponentInChildren<MeshRenderer>().material;
    if (StartDay)
    {
      currentTime = 0.3f; //start at morning
      nightMat.color = new Color(1f, 1f, 1f, 0f);
    }
  }
	
	// Update is called once per frame
	void Update () {
		UpdateLight();
		currentTime += (Time.deltaTime / SecondsInAFullDay) * timeMultiplier;
		if (currentTime >= 1) {
			currentTime = 0;//once we hit "midnight"; any time after that sunrise will begin.
			currentDay++; //make the day counter go up
		}
	}

	void UpdateLight()
	{
		StarDome.transform.Rotate (new Vector3 (0, 2f * Time.deltaTime, 0));
		moon.transform.LookAt (targetCam.transform);
		directionalLight.transform.localRotation = Quaternion.Euler ((currentTime * 360f) - 90, 170, 0);
		moonState.transform.localRotation = Quaternion.Euler ((currentTime * 360f) - 100, 170, 0);
		//^^ we rotate the sun 360 degrees around the x axis, or one full rotation times the current time variable. we subtract 90 from this to make it go up
		//in increments of 0.25.

		//the 170 is where the sun will sit on the horizon line. if it were at 180, or completely flat, it would be hard to see. Tweak this value to what you find comfortable.

		float intensityMultiplier = 1;

		if (currentTime <= 0.23f || currentTime >= 0.75f) 
		{
			intensityMultiplier = 0; //when the sun is below the horizon, or setting, the intensity needs to be 0 or else it'll look weird
      starMat.color = new Color(1,1,1,Mathf.Lerp(1,0,Time.deltaTime));
      
    }
		else if (currentTime <= 0.25f) 
		{
     
      intensityMultiplier = Mathf.Clamp01((currentTime - 0.23f) * (1 / 0.02f));
			starMat.color = new Color(1,1,1,Mathf.Lerp(0,1,Time.deltaTime));
      
    }
		else if (currentTime <= 0.73f) 
		{
      
      intensityMultiplier = Mathf.Clamp01(1 - ((currentTime - 0.73f) * (1 / 0.02f)));
    
    }


		//change env colors to add mood

		if (currentTime <= 0.2f) {
			RenderSettings.ambientSkyColor = Color.Lerp(RenderSettings.ambientSkyColor, nightColors.skyColor,Time.deltaTime);
			RenderSettings.ambientEquatorColor = Color.Lerp(RenderSettings.ambientEquatorColor, nightColors.equatorColor, Time.deltaTime);
			RenderSettings.ambientGroundColor = Color.Lerp(RenderSettings.ambientGroundColor, nightColors.horizonColor, Time.deltaTime);
    }
		if (currentTime > 0.2f && currentTime < 0.4f) {
			RenderSettings.ambientSkyColor = Color.Lerp(RenderSettings.ambientSkyColor, dawnColors.skyColor, Time.deltaTime);
			RenderSettings.ambientEquatorColor = Color.Lerp(RenderSettings.ambientEquatorColor, dawnColors.equatorColor, Time.deltaTime);
			RenderSettings.ambientGroundColor = Color.Lerp(RenderSettings.ambientGroundColor, dawnColors.horizonColor, Time.deltaTime);
      
    }
		if (currentTime > 0.4f && currentTime < 0.75f) {
			RenderSettings.ambientSkyColor = Color.Lerp(RenderSettings.ambientSkyColor, dayColors.skyColor, Time.deltaTime);
			RenderSettings.ambientEquatorColor = Color.Lerp(RenderSettings.ambientEquatorColor, dayColors.equatorColor, Time.deltaTime);
			RenderSettings.ambientGroundColor = Color.Lerp(RenderSettings.ambientGroundColor, dayColors.horizonColor, Time.deltaTime);
     
    }
		if (currentTime > 0.75f) {
			RenderSettings.ambientSkyColor = Color.Lerp(RenderSettings.ambientSkyColor, dayColors.skyColor, Time.deltaTime);
			RenderSettings.ambientEquatorColor = Color.Lerp(RenderSettings.ambientEquatorColor, dayColors.equatorColor, Time.deltaTime);
			RenderSettings.ambientGroundColor = Color.Lerp(RenderSettings.ambientGroundColor, dayColors.horizonColor, Time.deltaTime);
      
    }

		directionalLight.intensity = lightIntensity * intensityMultiplier;
	}

	public string TimeOfDay ()
	{
	string dayState = "";
		if (currentTime > 0f && currentTime < 0.1f) {
			dayState = "Midnight";
      if (timeLeft <= Time.deltaTime)
      {
        //nightMat.color = new Color(0.1580634f, 0.1817454f, 0.3018868f, 0.9f);

        // transition complete
        // assign the target color
        nightMat.color = targetColor;

        // start a new transition
        targetColor = new Color(0.1580634f, 0.1817454f, 0.3018868f, 0.9f);
        timeLeft = 1.0f;
      }
      else
      {
        // transition in progress
        // calculate interpolated color
        nightMat.color = Color.Lerp(nightMat.color, targetColor, Time.deltaTime / timeLeft);

        // update the timer
        timeLeft -= Time.deltaTime;
      }
    }
    
		if (currentTime < 0.5f && currentTime > 0.1f)
		{
			dayState = "Morning";
      //nightMat.color = new Color(0.8490566f, 0.6047526f, 0.8155605f, 0.5f);
      if (timeLeft <= Time.deltaTime)
      {

        // transition complete
        // assign the target color
        nightMat.color = targetColor;

        // start a new transition
        targetColor = new Color(0.8490566f, 0.6047526f, 0.8155605f, 0.5f);
        timeLeft = 1.0f;
      }
      else
      {
        // transition in progress
        // calculate interpolated color
        nightMat.color = Color.Lerp(nightMat.color, targetColor, Time.deltaTime / timeLeft);

        // update the timer
        timeLeft -= Time.deltaTime;
      }
    }
		if (currentTime > 0.5f && currentTime < 0.6f)
		{
			dayState = "Mid Noon";
      //nightMat.color = new Color(0.2755005f, 0.2367391f, 0.3773585f, 0f);
      if (timeLeft <= Time.deltaTime)
      {

        // transition complete
        // assign the target color
        nightMat.color = targetColor;

        // start a new transition
        targetColor = new Color(0.2755005f, 0.2367391f, 0.3773585f, 0f);
        timeLeft = 1.0f;
      }
      else
      {
        // transition in progress
        // calculate interpolated color
        nightMat.color = Color.Lerp(nightMat.color, targetColor, Time.deltaTime / timeLeft);

        // update the timer
        timeLeft -= Time.deltaTime;
      }
    }
		if (currentTime > 0.6f && currentTime < 0.8f)
		{
			dayState = "Evening";
      //nightMat.color = new Color(0.6218847f, 0.3571111f, 0.7075472f, 0.5f);
      if (timeLeft <= Time.deltaTime)
      {

        // transition complete
        // assign the target color
        nightMat.color = targetColor;

        // start a new transition
        targetColor = new Color(0.6218847f, 0.3571111f, 0.7075472f, 0.5f);
        timeLeft = 1.0f;
      }
      else
      {
        // transition in progress
        // calculate interpolated color
        nightMat.color = Color.Lerp(nightMat.color, targetColor, Time.deltaTime / timeLeft);

        // update the timer
        timeLeft -= Time.deltaTime;
      }
    }
		if (currentTime > 0.8f && currentTime < 1f)
		{
			dayState = "Night";
      // nightMat.color = new Color(0.2755005f, 0.2367391f, 0.3773585f, 0.8f);
      if (timeLeft <= Time.deltaTime)
      {

        // transition complete
        // assign the target color
        nightMat.color = targetColor;

        // start a new transition
        targetColor = new Color(0.2755005f, 0.2367391f, 0.3773585f, 0.8f);
        timeLeft = 1.0f;
      }
      else
      {
        // transition in progress
        // calculate interpolated color
        nightMat.color = Color.Lerp(nightMat.color, targetColor, Time.deltaTime / timeLeft);

        // update the timer
        timeLeft -= Time.deltaTime;
      }
    }
		return dayState;
	}

	void OnGUI()
	{
		//debug GUI on screen visuals
		if (showUI) {
			GUILayout.Box (":grin:ay: " + currentDay);
			GUILayout.Box (TimeOfDay ());
			GUILayout.Box ("Time slider":wink:;
			GUILayout.VerticalSlider (currentTime, 0f, 1f);
		}
	}
}
« Last Edit: May 17, 2022 @789.35 by Melooon » Logged

Melooon
Hero Member ⚓︎
*****


So many stars!

SpaceHey: Friend Me!
StatusCafe: melon
iMood: Melonking
Itch.io: My Games

View Profile WWW

Thanks for being rad!a puppy for your travelsAlways My PalFirst 1000 Members!spring 2023!Squirtle!!!!MIDI WarriorMIDI Warrior1234 Posts!OzspeckCool Dude AwardRising Star of the Web AwardMessage BuddyPocket Icelogist!OG! Joined 2021!...
« Reply #1 on: May 17, 2022 @786.75 »

Heck, that's a lot of code! I didn't read it all and this seems like more of a mathematical question and I'm more of a trial and error kinda programmer BUT I will try and guess:

This is your random code?
Code
int chanceRain = Random.Range(1, 2);
randomWeather = chanceRain * date;

if (randomWeather%2==1)
{
 particles.SetActive(true);
}

if (randomWeather%2==0)
{
 particles.SetActive(false);
}

Sooo random range 1 - 2 will give your a 1 or a 2. Multiplying it by a date (which is an incremental number) means it will always be even or odd and 1 or 2. I suspect that's why its happening (almost) every other day, its a super small range being influenced by a sequential even or odd number, so each time the remainder will go 1 2 1 2 1 2 etc. (That's totally a guess)

Anyway, one solution would be to do wit with percentages instead.
Code
if(A NEW DAY HAS STARTED)
{
 int chanceRain = Random.Range(0, 100);

 if (chanceRain > 50)
 {
  particles.SetActive(true);
 }
 else
 {
  particles.SetActive(false);
 }
}

In this case you have a 50% chance of rain each update, you could change that 50 to another number, or even another random number to make it even more random. That might be waaaayyy too high a chance, but you can mess with the numbers to fix that.. eg Random.Range(0, 99999) or something.
« Last Edit: May 17, 2022 @811.53 by Melooon » Logged


everything lost will be recovered, when you drift into the arms of the undiscovered
Pages: [1] Print 
« previous next »
 

Vaguely similar topics! (3)

What is an extremely messy way to write a hello world script?

Started by Icey!Board ☔︎ ∙ I need Help!

Replies: 9
Views: 2340
Last post September 03, 2023 @739.02
by Kallistero
Random Art Generator ! ! !

Started by ellievoyydBoard ☆ ∙ Showcase & Links

Replies: 8
Views: 2412
Last post February 03, 2022 @753.85
by Darmodej
Putting JS script inside of an HTML table?

Started by tarraxahumBoard ☔︎ ∙ I need Help!

Replies: 3
Views: 742
Last post December 17, 2022 @869.95
by tarraxahum

Melonking.Net © Always and ever was! SMF 2.0.19 | SMF © 2021, Simple Machines | Terms and Policies Forum Guide | Rules | RSS | WAP2


MelonLand Badges and Other Melon Sites!

MelonLand Project! Visit the MelonLand Forum! Support the Forum
Visit Melonking.Net! Visit the Gif Gallery! Pixel Sea TamaNOTchi