Game Bucks

Flashlight Script v2.1.1

This is a script that contains a battery system and dims the intensity of the light as the battery charge gets lower. Just attach this to any spotlight which is attached to the player and modify the lifetime of the flashlight battery in the inspector.

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Light), typeof(AudioSource))]
public class Flashlight : MonoBehaviour {
	public AudioClip clickSound;
	public float batteryLifeInSec = 300f;
	public float batteryPercentage = 100;
	
	private bool on;
	private float timer;

	void Update() {
		Light lite = GetComponent<Light>();
		timer += Time.deltaTime;
	
		if(Input.GetKeyDown(KeyCode.F) && timer >= 0.3f && batteryPercentage > 0) {
			on = !on;
                        audio.PlayOneShot(clickSound);
			timer = 0;
		}
	
		if(on) {
			lite.enabled = true;
			batteryPercentage -= Time.deltaTime * (100 / batteryLifeInSec);
		}
		else {
			lite.enabled = false;
		}
	
		batteryPercentage = Mathf.Clamp(batteryPercentage, 0, 100);
	
		if(batteryPercentage == 0) {
			lite.intensity = Mathf.Lerp(lite.intensity, 0, Time.deltaTime * 2);
		}
		
		if(batteryPercentage > 0 && batteryPercentage < 25) {
			lite.intensity = Mathf.Lerp(lite.intensity, 0.5f, Time.deltaTime);
		}
		
		if(batteryPercentage > 25 && batteryPercentage < 75) {
			lite.intensity = Mathf.Lerp(lite.intensity, 0.8f, Time.deltaTime);
		}
		
		if(batteryPercentage > 75 && batteryPercentage <= 100) {
			lite.intensity = Mathf.Lerp(lite.intensity, 1, Time.deltaTime);
		}
	}
}

Game Bucks

Add comment

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.