Search Unity

Need help with flashlight script

Discussion in 'Scripting' started by green_enigma_games, Sep 20, 2014.

  1. green_enigma_games

    green_enigma_games

    Joined:
    Jan 25, 2014
    Posts:
    3
    Hello everyone, I'm new to the forums, and still fairly new to Unity. I heard the forums were very helpful, so I figured I'd seek help here.

    What I have is a flashlight script, which I have pieced together from a few different example scripts I found on "Unity Answers". I'm still learning Javascript, as I am used to DarkBasic and BlitzBasic. Here is the problem I am having. The script basically adds a spot light to a FPS Controller. You can turn the light on and off by pressing "F", and it has a battery life that counts down, then turns the light off when the battery is drained. I'm having one minor and one major issue.

    Minor: When I start the game the flash light is automatically on. I have to turn it off, then back on for the battery to start draining.

    Major: I have a GUI Bar that is supposed to show the battery life draining, unfortunately the batter drains, but the GUI does not change.

    Also: Another Issue I am having, and I'm not sure if there is a way around this, when I start up the game, the Health and Battery Bars I have, do not start full. The game starts, and then the two bars slowly fill up. If I can figure how to fix this on the Battery, then I can fix it on the Health Bar, because they are similarly scripted.

    Here is my Flashlight Script
    Code (JavaScript):
    1.     //Name this script Flashlight and attach it to your player for instance
    2.    
    3.     var lightSource : Light; //Connect the light source in the Inspector
    4.     static var maxEnergy : float = 100; //The energy amount of the flashlight
    5.     private var currentPower;
    6.     var turnedOn : boolean = false; //Boolean to check whether it's turned on or off
    7.     var drainSpeed : float = 2.0; //The speed that the energy is drained
    8.     private var alpha : float;
    9.     private var duration : float = 0.2;
    10.     private var baseIntensity : float;
    11.        var batteryDisplay : float = 0;
    12.     var pos : Vector2 = new Vector2(20,10);
    13.     var size : Vector2 = new Vector2(100,20);
    14.     var batteryBarEmpty : Texture2D;
    15.     var batteryBarFull : Texture2D;
    16.    
    17.     function Update () {
    18.    
    19.     batteryDisplay = Time.time * 0.05;
    20.    
    21.     if (Input.GetKeyDown(KeyCode.F)) ToggleFlashlight();
    22.     if(currentPower < maxEnergy/4 && lightSource.enabled){
    23.     var phi : float = Time.time / duration * 2 * Mathf.PI;
    24.     var amplitude : float = Mathf.Cos( phi ) * .5 + baseIntensity;
    25.     lightSource.light.intensity = amplitude + Random.Range(0.1, 1.0) ;
    26.     }
    27.     lightSource.light.color = Color(alpha/maxEnergy, alpha/maxEnergy, alpha/maxEnergy, alpha/maxEnergy);
    28.     alpha = currentPower;
    29.    
    30.     if (turnedOn==true) {
    31.     if(currentPower > 0.0) currentPower -= Time.deltaTime * drainSpeed;
    32.     if(currentPower <= 0.0) {lightSource.enabled = false;}
    33.     }
    34.     if (turnedOn==false) {
    35.     if(currentPower < maxEnergy) currentPower += Time.deltaTime * drainSpeed/2;
    36.     }
    37.     }
    38.    
    39.     //When the player press F we toggle the flashlight on and off
    40.     function ToggleFlashlight () {
    41.     turnedOn=!turnedOn;
    42.     if (turnedOn && maxEnergy>0) {
    43.     TurnOnAndDrainEnergy();
    44.     } else {
    45.     lightSource.enabled = false;
    46.     }
    47.     }
    48.    
    49.     //When the flashlight is turned on we enter a while loop which drains the energy
    50.     function TurnOnAndDrainEnergy () {
    51.     lightSource.enabled = true;
    52.     while (turnedOn && maxEnergy>0) {
    53.     maxEnergy -= drainSpeed*Time.deltaTime;
    54.     yield;
    55.     }
    56.     lightSource.enabled = false;
    57.     }
    58.    
    59.     //This is called from outside the script to alter the amount of energy
    60.     static function AlterEnergy (amount : int) {
    61.     maxEnergy = Mathf.Clamp(maxEnergy+amount, 0, 100);
    62.     }
    63.    
    64.     //Display current battery on your flashlight
    65.      function OnGUI()
    66.     {
    67.    
    68.     // draw the background:
    69.     GUI.BeginGroup (new Rect (pos.x, pos.y, size.x, size.y));
    70.     GUI.Box (Rect (0,0, size.x, size.y),batteryBarEmpty);
    71.    
    72.     // draw the filled-in part:
    73.     GUI.BeginGroup (new Rect (0, 0, size.x * batteryDisplay, size.y));
    74.     GUI.Box (Rect (0,0, size.x, size.y),batteryBarFull);
    75.     GUI.EndGroup ();
    76.    
    77.     GUI.EndGroup ();
    78.    
    79.     }
    If anyone can help, I would humbly appreciate it. I hope I've made this clear enough to understand.

    Thanks in advance!
     
  2. ChrisSch

    ChrisSch

    Joined:
    Feb 15, 2013
    Posts:
    763
    Whatever you want to happen at the start of the script, you make a start function.

    Like so:


    Code (JavaScript):
    1. function Start()
    2. {
    3. //have your flashlight off here
    4. //or set the battery var to full
    5. }
    Here's my old flashlight script. It could be probably more optimized but its shorter and simpler than yours. Just fill in all the stuff in the inspector like the GUI text youll use for percentage. Or change whatever you want. Or just study it.

    Code (JavaScript):
    1. var Light = false;
    2. var lightOff = true;
    3. var battery : float = 100;
    4. var batteryDrainSpeed : float = 1;
    5. var haveBattery : boolean = true;
    6. var batteryPercentage : GUIText;
    7. var myGUI : GUISkin;
    8. var batteryFull = true;
    9. var batteryChargeSpeed : float = 0.2;
    10.  
    11. function OnGUI()
    12. {
    13.     GUI.skin = myGUI;
    14. }
    15.  
    16. function Update()
    17. {
    18.     if(Input.GetButtonDown("Flashlight") && lightOff && haveBattery)
    19.     {
    20.         light.enabled = true;
    21.         lightOff = false;
    22.     }
    23.     else if(Input.GetButtonDown("Flashlight") && !lightOff)
    24.     {
    25.         light.enabled = false;
    26.         lightOff = true;
    27.     }
    28.     if(battery < 0)
    29.     {
    30.         battery = 0;
    31.         haveBattery = false;
    32.     }
    33.     else if(battery > 0)
    34.     {
    35.         haveBattery = true;
    36.     }
    37.     if(battery == 0)
    38.     {
    39.         light.enabled = false;
    40.         lightOff = true;
    41.         haveBattery = false;
    42.     }
    43.     batteryPercentage.text = "Flashlight: "+battery.ToString("F0")+" %";
    44.     if(haveBattery && !lightOff)
    45.     {
    46.         battery-=(batteryDrainSpeed * Time.deltaTime);
    47.     }
    48.     if(lightOff && !batteryFull)
    49.     {
    50.         battery+=(batteryChargeSpeed * Time.deltaTime);
    51.     }
    52.     if(battery > 100)
    53.     {
    54.         batteryFull = true;
    55.         battery = 100;
    56.     }
    57.     else if(battery < 100)
    58.     {
    59.         batteryFull = false;
    60.     }
    61.  
    62. }
    63.  
    64. function OnEnable()
    65. {
    66.     batteryPercentage.guiText.enabled = true;
    67.     batteryPercentage.text = "Flashlight: "+battery.ToString("F0")+" %";
    68. }
    69.  
    70. function OnDisable()
    71. {
    72.     if(batteryPercentage)
    73.     {
    74.         batteryPercentage.guiText.enabled = false;
    75.     }
    76. }
    Also if I may suggest, switch to C# as soon as possible. Unityscript is fading away slowly and most assets you download will be in C#. Don't worry they're not much different.
     
  3. BmxGrilled

    BmxGrilled

    Joined:
    Jan 27, 2014
    Posts:
    239
    Here's some flashlight scripts in C#
    (one requires the other through inheritence, but you only need to drag the one you want to use onto your character, and you set their states in variables or in the start function)

    Code (CSharp):
    1. //FlashlightToggle.cs
    2. //C#
    3. using UnityEngine;
    4. using System.Collections;
    5.  
    6. //this script requires a Light to be attached to the same gameObject
    7. [RequireComponent(typeof(Light))]
    8. public class FlashlightToggle : MonoBehaviour
    9. {
    10.     protected Light _lightSource;    //cache our light source component
    11.     [SerializeField]                /*    allow us to set whether the flashlight
    12.                                         is on or off at the start of the level    */
    13.     private bool _toggle;            //internal toggle value
    14.     public bool toggle                //public toggle getter/setter
    15.     {
    16.         get { return _toggle; }        //return stored internal value
    17.         set
    18.         {
    19.             bool wasToggle = _toggle;    //we need to know whether the flashlight was on or off before we change the value
    20.             _toggle = value;            //set the new value
    21.            
    22.             //if the value has changed, trigger the flashlight toggle event
    23.             if (_toggle != wasToggle) { OnFlashlightToggle(_toggle); }
    24.         }
    25.     }
    26.    
    27.     //use this to initialize component references and variables
    28.     public virtual void Awake()
    29.     {
    30.         _lightSource = gameObject.GetComponent<Light>();
    31.         _lightSource.enabled = _toggle;
    32.     }
    33.    
    34.     //flashlight toggle event
    35.     protected virtual void OnFlashlightToggle(bool state)
    36.     {
    37.         _lightSource.enabled = state;    //switch the light source on or off
    38.     }
    39. }
    40.  
    Code (CSharp):
    1. //FlashlightBattery.cs
    2. //C#
    3. using UnityEngine;
    4. using System.Collections;
    5.  
    6. public class FlashlightBattery : FlashlightToggle
    7. {
    8.     public float lifetime;            //how long the battery lasts (seconds)
    9.     public float blinkTime;            //at the end of the battery life, how long to fade (seconds)
    10.     private float _timer;            //for counting seconds
    11.     private float _intensity;        //for storing default intensity
    12.     public float blinkIntensity;    //what intensity to fade to at the end of the battery life
    13.     public float chargeRate;        //how many seconds to full charge
    14.    
    15.     //this returns a value between 0.0f and 1.0f, a percentage of the battery life left
    16.     public float charge { get { return _timer / lifetime; } }
    17.    
    18.     //use this to initialize script references and variables
    19.     public override void Awake()
    20.     {
    21.         base.Awake();
    22.         _timer = lifetime;
    23.         _intensity = _lightSource.intensity;
    24.     }
    25.    
    26.     //flashlight toggle event inherited from FlashlightToggle
    27.     protected override void OnFlashlightToggle(bool state)
    28.     {
    29.         base.OnFlashlightToggle(state);
    30.         if (state)
    31.         {//if we're turning the flashlight on
    32.             if (_timer <= 0) { toggle = false; return; }    //check to make sure we have battery life first
    33.             _lightSource.intensity = _intensity;            //if we do, reset the light intensity to full
    34.         }
    35.     }
    36.    
    37.     //this runs every frame
    38.     public void Update()
    39.     {
    40.         if (toggle)
    41.         {//the flashlight is on
    42.             if (_timer > 0)
    43.             {//deduce battery life over time
    44.                 _timer -= Time.deltaTime;
    45.                 if (_timer <= blinkTime)
    46.                 {//fade light intensity to blinkIntensity when we reach blinkTime
    47.                     _lightSource.intensity = Mathf.Lerp(blinkIntensity, _intensity, _timer / blinkTime);
    48.                 }
    49.             }
    50.             else
    51.             {//switch off when the battery life runs out
    52.                 _timer = 0;
    53.                 toggle = false;
    54.             }
    55.         }
    56.         else if (_timer < lifetime)
    57.         {//the flashlight is off, recharge the battery
    58.             _timer += Time.deltaTime / (chargeRate / lifetime);
    59.             if (_timer > lifetime) { _timer = lifetime; }
    60.         }
    61.     }
    62. }
    63.  
    The FlashlightBattery is the battery script. Hopefully you'll be able to see some similarities between JS(UnityScript) and C#
    Hope this helps! :)