After solving a ReferenceError with my Flash_Light.cs
script, I've been having an issue where the target light in the script won't flash.
The Flash_Light
script is attached to LampPost_A_Blink1
,LampPost_A_Blink1
has a light attached (called RedLight
), and the script seems to work perfectly (no warnings or errors). However, the light won't flash.
My script is:
using UnityEngine;
using System.Collections;
public class Blink_Light : MonoBehaviour
{
public float totalSeconds = 2; // The total of seconds the flash wil last
public float maxIntensity = 8; // The maximum intensity the flash will reach
public Light myLight;
void Awake()
{
//Find the RedLight
GameObject redlight = GameObject.Find("LampPost_A_Blink1/RedLight");
//Get the Light component attached to it
myLight = redlight.GetComponent<Light>();
}
public IEnumerator flashNow()
{
float waitTime = totalSeconds / 2;
// Get half of the seconds (One half to get brighter and one to get darker)
while (myLight.intensity < maxIntensity)
{
myLight.intensity += Time.deltaTime / waitTime; // Increase intensity
}
while (myLight.intensity > 0)
{
myLight.intensity -= Time.deltaTime / waitTime; //Decrease intensity
}
yield return null;
}
}
When entering playmode, the light stays illuminated, instead of blinking like it should.
How can I fix this? (I have Unity 2017.2.0f3)
Unity's Time.deltaTime
will be the-same in a function or a loop in a function. It changes every frame but calling a function once is one frame. The problem is that you used it in a while
loop without waiting for the next frame so you get the-same value.
Also, because you are not waiting for a frame, instead of the code executing over multiple frames, it will execute in one frame only and you won't be able to see the changes on the light. The solution to this is to put yield return null
in each while
loop. It will make the code in the while
loop run every frame until the condition is met then it exit.
public IEnumerator flashNow()
{
float waitTime = totalSeconds / 2;
// Get half of the seconds (One half to get brighter and one to get darker)
while (myLight.intensity < maxIntensity)
{
myLight.intensity += Time.deltaTime / waitTime; // Increase intensity
//Wait for a frame
yield return null;
}
while (myLight.intensity > 0)
{
myLight.intensity -= Time.deltaTime / waitTime; //Decrease intensity
//Wait for a frame
yield return null;
}
yield return null;
}
Since this is a caroutine function, don't forget to call or start it with StartCoroutine(flashNow())
: