- Home /
Random switch enum with a delay
I have this script( i whant when it happends like 15 seconds the enum type switch to cloudy and in cloudy when its happend 10 seconds switchs to sunny ) I want that loop to repeat all the time.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CloudSystem : MonoBehaviour
{
public enum SkyType {Sunny,Cloudy};
public SkyType skyType;
public float changeSpeed = 0.01f;
private float cutOff;
public Material cloudMaterial;
private void Start()
{
cloudMaterial.SetFloat("_CutOff", 0); //Sets the cloudMaterial CutOff to 0 in the Start;
cutOff = cloudMaterial.GetFloat("_CutOff"); //Get the CutOff value to cutOff
}
void Update()
{
//Can Switch between Skys
switch (skyType)
{
case SkyType.Cloudy:
Cloudy();
break;
case SkyType.Sunny:
Sunny();
break;
}
}
void Cloudy()
{
cutOff = Mathf.MoveTowards(cutOff, 0.35f, changeSpeed * Time.deltaTime);
cloudMaterial.SetFloat("_CutOff", cutOff);
}
void Sunny()
{
cutOff = Mathf.MoveTowards(cutOff, 0, changeSpeed * Time.deltaTime);
cloudMaterial.SetFloat("_CutOff", cutOff);
}
}
Answer by lgarczyn · Jan 13, 2020 at 03:18 AM
First, currently your start function can simply be this
private void Start()
{
Sunny();
}
You should also make cutoff
a function variable, instead of a private variable.
Now, you should probably use Coroutines for this, something like
IEnumerator WeatherCoroutine()
{
while (true)
{
Sunny();
yield return new WaitForSeconds(15f);
Cloudy();
yield return new WaitForSeconds(10f);
}
}
To call this, simply remove the update code and change start to
private void Start()
{
StartCoroutine(WeatherCoroutine());
}
Now instead of hardcoded time values, you can have two public variables for the sunny duration and the cloudy duration, that are used inside the coroutine to set the wait duration.
Your answer
Follow this Question
Related Questions
Point Counter Works Only Once! 1 Answer
How to double spirte/gameobject/prefab and control the result on those items? 0 Answers
How would I access my list from another function? 1 Answer
Shooting with get joint rotation .eulerAngles kinect 0 Answers
Help with a simple procedural generation 0 Answers