Changing Color of Object Using a Timer
I am having a issue creating a timer that changes the color of my traffic light. This is the code that I currently have. I have two different scripts. One for a State Machine and one for the Lights.
private bool isGreen = true;
private bool isYellow = true;
private bool isRed = true;
private float timePassed = Time.deltaTime ++;
bool IsLightGreen()
{
return isGreen;
}
bool IsLightYellow()
{
return isYellow;
}
bool IsLightRed()
{
return isRed;
}
void ToggleLight()
{
isGreen = !isGreen;
isYellow = !isYellow;
isRed = !isRed;
}
}
I am probably going all about this wrong but I keep researching time and color changing and all I can find is posts about using java script which I have a hard time reading and translating it to C#. Any suggestions would be great. Keep in mind I am super beginner and am in college still learning C#.
Thanks
Answer by Cynikal · Oct 30, 2016 at 06:07 PM
A simple timer:
float _t = 0f;
void Update()
{
_t += Time.deltaTime;
if (_t >= TheNumberOfSecondsIWant)
{
_t = 0f;
TriggerTheLight();
}
}
I would actually probably set it up to trigger a coroutine, that i'd have cycle through the red/yellow/green light.
It has to go from green to yellow to red... I will try to implement what you showed me. $$anonymous$$aybe my brain will start working correctly lol.
If you change per my example:
_t = 0f; TriggerTheLight();
to:
_t = 0f; StartCoroutine(TriggerTheLight());
You could then do:
IEnumerator TriggerTheLight() {
GreenLight.Enabled = false;
YellowLight.Enabled = true;
RedLight.Enabled = false;
yield return new WaitForSeconds(1f);
GreenLight.Enabled = false;
YellowLight.Enabled = false;
RedLight.Enabled = true;
}
First off, your timer is wrong.
if (_t >= TheTimeInSecondsYouWantGoesHere) { _t = 0f; StartCoroutine(TriggerTheLight()); }
As far as the Green/yellow/redlight.enabled stuff,
You need to declare variables.
public GameObject GreenLight; public GameObject YellowLight; public GameObject RedLight;
then assign them to their respective objects.
The purpose of Unity Answers is not for someone else to write your script for you, but to point you in the right direction. You'll need to modify and adapt the code accordingly.
Well I know Im not supposed to have someone write the code for me. I did learn quite a bit going back and forth. I will get this done thanks for the help.
Your answer
Follow this Question
Related Questions
,Why isn't the clock speed being affected by the float "clockSpeed"? 0 Answers
Time.deltaTime timer counting slowly 3 Answers
Disable Ragdoll #C - Timer before disable. 2 Answers
Respawn issues 2 Answers
Can somebody help me fix this script? 2 Answers