- Home /
Flashlight Flickering
Hello Unity members id like to make my flashlight (that runs on batteries) flickering when the battery is low heres my script(its made in c#):
using UnityEngine; using System.Collections;
public class Flashlight : MonoBehaviour { public static float BatteryLife = 100; public static GameObject HeadLightMount;
public Light HeadLight;
public float BatteryReductionSpeed = 3.0f;
public AudioClip on;
public AudioClip off;
private AudioSource audiosource;
void Awake()
{
audiosource = GameObject.Find("Main Camera").GetComponent<AudioSource>();
HeadLightMount = GameObject.FindWithTag("Headlamp");
HeadLight.enabled = false;
}
void Update()
{
if(HeadLight.enabled)
{
BatteryLife = BatteryLife - (BatteryReductionSpeed * Time.deltaTime);
}
if(Input.GetKeyDown(KeyCode.F) && HUD.HasFlashlight && !HeadLight.enabled)
{
audiosource.clip = on;
audiosource.Play();
if(BatteryLife <= 0 && HUD.BatteryCount > 0)
{
HUD.BatteryCount--;
BatteryLife = 100;
}
HeadLight.enabled = true;
}
else if(Input.GetKeyDown(KeyCode.F) && HUD.HasFlashlight && HeadLight.enabled)
{
audiosource.clip = off;
audiosource.Play();
HeadLight.enabled = false;
}
if(BatteryLife <= 0)
{
BatteryLife = 0;
HeadLight.enabled = false;
}
}
}
Answer by sfc.itzhak · Aug 19, 2013 at 11:09 AM
hey mate,
you have 2 options:
1.writing a script or a function that turns on and off the flashlight to simulate flickering.
2.do an animation of this flickering and playing it.
i prefer the animation cause it gives you more freadom and can look more real and dynamic then doing it in a script,
script sample:
add this function and call it by " StartCoroutine(FlashLightFlicker());"
IEnumerator FlashLightFlicker()
{
while (true)
{
HeadLight.enabled = !HeadLight.enabled;
yield return new WaitForSeconds(Random.Range(0,1));
}
}
and see the animation in the attached package.
sfc
I dont understand what u mean by that script im kind of a noob, cant you put it in too my script ? :/
you have a link just download and import and see for yourself
sfc.
@StickyDream - I understand that you're trying to write a game and get some help here, but without proper knowledge, you will not be able to complete what you wish.
I strongly suggest reading through Unity documentation, watching the tutorials and checking pages like Unity Gems. You will spend some time on this, true, but then you'll understand other people answers.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Flashlight Flicker! 2 Answers
Flashlight turning off, but not back on again? 4 Answers
Flashlight won't turn off. 2 Answers
Flashlight effect 2 Answers