I want to implement a simple traffic light in unity . The traffic light game object will forever do just the below things.
- Red will turn on once game starts
- wait till 10 sec
- Yellow will turn on
- wait till 3 sec
- Green will turn on
- Wait for 10 sec before red turns on.
Please help me . As of now only red and yellow lights up but green wont turn on.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
namespace open_world
{
public class traffic_light : MonoBehaviour
{
public Light red_traffic_light;
public Light yellow_traffic_light;
public Light green_traffic_light;
void Start()
{
StartCoroutine(traffic());
}
IEnumerator traffic()
{
while(true){
red_traffic_light.GetComponent().intensity = 30;
yield return new WaitForSeconds(10);
yellow_traffic_light.GetComponent().intensity = 30;
yield return new WaitForSeconds(3);
green_traffic_light.GetComponent().intensity = 30;
yield return new WaitForSeconds(10);
}
}
}
}
Hello, I think the problem is the GetComponent()
calls, which shouldn’t be needed. red_traffic_light
is a reference to a Light
component, so there’s no need to request a component before adjusting the light’s properties.
Calling GetComponent()
without providing a type isn’t valid code anyway, you’d need to tell it what component you’re looking for, such as GetComponent<MeshFilter>()
. But in this case you already have access to the Light
component that you’re interested in, so don’t need to do that at all.
using UnityEngine;
using System.Collections;
public class TrafficLight : MonoBehaviour
{
public Light Red;
public Light Yellow;
public Light Green;
void Start()
{
StartCoroutine(Traffic());
}
IEnumerator Traffic()
{
while (true)
{
Red.intensity = 3f;
Yellow.intensity = 0f;
Green.intensity = 0f;
yield return new WaitForSeconds(10f);
Red.intensity = 0f;
Yellow.intensity = 3f;
Green.intensity = 0f;
yield return new WaitForSeconds(3f);
Red.intensity = 0f;
Yellow.intensity = 0f;
Green.intensity = 3f;
yield return new WaitForSeconds(10f);
}
}
}
You might notice I set the intensity of all 3 lights for each phase. For some transitions that has no effect—the green light is already off when we enter the “yellow on” phase—but I think it makes the code’s purpose clearer. You may also want to consider turning the lights on and off by enabling/disabling the component rather than adjusting the intensity.