Cannot stop light flickering?
Basically, I want the player to walk through a trigger zone, and their flashlight starts to flicker. Using a great tutorial, and adding the trigger part of the script myself, I got this to work. But now I need the light to stop flickering. I've had a go at doing this myself, but I cannot get it to stop. I tried adding another variable called flickerTime which sets the time that the flicker lasts for before it stops. Here is my script:
EDIT: I tried using Invoke (FlickerDisable, flickerTime); but I got the same result as before. I have also tried creating another trigger zone which is in front of the first trigger zone which has this script on it (as an attempt to cancel out the first trigger zone), but still got the same result. I would much rather use one script than two separate triggers, although neither method works as of now:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FlashlightOn : MonoBehaviour {
public GameObject triggerZone;
public Light lightObject;
void Start ()
{
triggerZone = triggerZone.GetComponent<GameObject> ();
}
void OnTriggerEnter (Collider other)
{
lightObject.enabled = true;
lightObject.intensity = 1;
}
}
Main Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Flickering : MonoBehaviour
{
public Light lightObject;
public float minTimeOn;
public float maxTimeOn;
public float minTimeOff;
public float maxTimeOff;
public float minLight;
public float maxLight;
public float flickerTime;
public GameObject triggerZone;
private float waitTimeOn;
private float waitTimeOff;
void Start ()
{
triggerZone = triggerZone.GetComponent<GameObject> ();
}
void OnTriggerEnter (Collider other)
{
StartCoroutine ("FlickerDisable");
}
void FlashlightOn ()
{
lightObject.enabled = true;
lightObject.intensity = 1;
}
IEnumerator Flicker ()
{
if (lightObject.enabled == true) {
waitTimeOn = Random.Range (minTimeOn, maxTimeOn);
yield return new WaitForSeconds (waitTimeOn);
lightObject.enabled = false;
StartCoroutine ("Flicker");
}
else
{
waitTimeOff = Random.Range (minTimeOff, maxTimeOff);
yield return new WaitForSeconds (waitTimeOff);
lightObject.intensity = Random.Range (minLight, maxLight);
lightObject.enabled = true;
StartCoroutine ("Flicker");
}
}
IEnumerator FlickerDisable ()
{
StartCoroutine ("Flicker");
yield return new WaitForSeconds (flickerTime);
FlashlightOn ();
}
}
It looks like you've got what is basically an infinite recursive loop going here. Once you start that coroutine, it just keeps restarting itself and you never attempt to stop it. In your case, the easiest way to get it to stop would be to add StopCoroutine("Flicker");
on the line between yield return new WaitForSeconds (flickerTime);
and FlashlightOn();
in the "FlickerDisable()" method.
You would probably be better off if you got rid of the FlickerDisable() method and added a timer-controlled while loop to the Flicker() method.