- Home /
How Can I enable and then disable a light in unity after a certain time?
First off, I would just like to say that I am new to using Unity Answers (this is the first question I've asked), so if there is anyway I can improve this question, please let me know, thanks!
I am attempting to make a weapon system for my game. I have a point light on the end of the gun with a "LightManager" script attached to it. When my gun is fired, I get a reference to that script in my gun controller script, and call the MuzzleFlash() function.
Here is my code so for my light manager class so far:
public class LightManager : MonoBehaviour {
Light light;
// Use this for initialization
void Start () {
light = GetComponent<Light> ();
light.enabled = false;
}
// Update is called once per frame
void Update () {
}
public void MuzzleFlash() {
light.enabled = true;
// After 0.5f seconds
light.enabled = false;
}
}
In my MuzzleFlash function I enable and then disable a light, but right now it does this all in one frame. How would I be able to enable it, wait X amount of time, and then disable the light?
Answer by Bonfire-Boy · Aug 31, 2016 at 11:34 AM
The simplest way would be to use a coroutine like this
public void MuzzleFlash()
{
StartCoroutine(MuzzleFlashCR());
}
private IEnumerator MuzzleFlashCR()
{
light.enabled = true;
yield return new WaitForSeconds(0.5f);
light.enabled = false;
}