Hi guys,
Can I use another method instead of OnTriggerStay?
My car needs to know all time if the color is green, yellow or red.
Here is my old code:
/// Check if the car is near trafficlight
/// </summary>
/// <param name="other"></param>
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Car"))
{
if ((_yellow.enabled == true) || (_red.enabled == true))
other.gameObject.GetComponent<CarEngine>().IsStop = true;
else
other.gameObject.GetComponent<CarEngine>().IsStop = false;
}
}
/// <summary>
/// Check if the car is near trafficlight
/// </summary>
/// <param name="other"></param>
private void OnTriggerStay(Collider other)
{
if (other.gameObject.CompareTag("Car"))
{
if (_green.enabled == true)
other.gameObject.GetComponent<CarEngine>().IsStop = false;
else if ((_yellow.enabled == true) || (_red.enabled == true))
other.gameObject.GetComponent<CarEngine>().IsStop = true;
}
}
/// <summary>
/// Check if the car is not near trafficlight
/// </summary>
/// <param name="other"></param>
private void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Car"))
{
other.gameObject.GetComponent<CarEngine>().IsStop = false;
}
}
This is the single option that I have in mind:
/// <summary>
/// Update is called every frame, if the MonoBehaviour is enabled.
/// </summary>
private void Update()
{
if (_green == true)
foreach (var car in _listWithCars)
car.GetComponent<CarEngine>().IsStop = false;
}
/// <summary>
/// Check if the car is near trafficlight
/// </summary>
/// <param name="other"></param>
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Car"))
{
_listWithCars.Add(gameObject);
if ((_yellow.enabled == true) || (_red.enabled == true))
other.gameObject.GetComponent<CarEngine>().IsStop = true;
else
other.gameObject.GetComponent<CarEngine>().IsStop = false;
}
}
/// <summary>
/// Check if the car is not near trafficlight
/// </summary>
/// <param name="other"></param>
private void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Car"))
{
if (_listWithCars.Contains(other.gameObject))
_listWithCars.Remove(other.gameObject);
other.gameObject.GetComponent<CarEngine>().IsStop = false;
}
}