Hello !
Im working on a game in the dark where you need battery for your flashlight. This is the script for the flashlight.
var Flashlight : Light; //Connect the light source in the Inspector
var LightOn : boolean = true;
var LightDrainSpeed : float = 0.1;
var BatteryLife : float = 0.0;
var MaxBatteryLife : float = 1.5;
function Update () {
if (LightOn && BatteryLife >= 0)
{
BatteryLife -= LightDrainSpeed * Time.deltaTime;
}
Flashlight.light.intensity = BatteryLife;
if(BatteryLife <= 0)
{
Batterylife = 0;
}
if(Input.GetKeyUp(KeyCode.F))
{
if(LightOn)
{
LightOn = false;
}
else if(!LightOn && BatteryLife >= 0)
{
LightOn = true;
}
Lighten();
}
}
function Lighten(){
if(LightOn)
{
Flashlight.light.active = true;
}
else
{
Flashlight.light.active = false;
}
}
I want to make a GUI to show how many percent left to the battery
and i want to make a gameObject Battery when you press E the battery life become 100 %.
Please and Thank you.
Add this code to your script: it displays the charge in percentage with the GUI system, and also has a function to recharge when the battery is picked up:
function OnGUI(){
var charge = 100 * BatteryLife/MaxBatteryLife;
GUI.Label(Rect(20,20,100,40), charge.ToString("F0")+"%");
}
function ChargeBattery(){ // function called by battery pickup
BatteryLife = MaxBatteryLife; // sets full charge
}
The battery pick up must have a trigger: when the player enters the trigger, its script verifies the key E - if pressed, the pickup charges the flashlight and suicides. The pickup script could be something like this:
EDITED: Oops! My bad: the event should be OnTriggerStay!
function OnTriggerStay(other: Collider){
if (other.tag == "Player" && Input.GetKeyDown("e")){
// call the function ChargeBattery in the player or its children:
other.BroadcastMessage("ChargeBattery");
Destroy(gameObject); // destroy the pickup
}
}
NOTE: The flashlight script must be attached to the player or to one of its children in order to be called by BroadcastMessage.