Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Flashlight batteries; collect and save for later (how to?)

Discussion in 'Scripting' started by RichardUnity, Jan 10, 2016.

  1. RichardUnity

    RichardUnity

    Joined:
    Jan 3, 2016
    Posts:
    13
    First of all, hello to everybody here!

    So, after loads of forum reading and tutorial watching I'm finally working on my first 'real' unity demo project!

    I'm trying to build as many 'horror-survival' based stuff to learn myself the basics, and hopefully ever be able to build all the game ideas that are in my head until now!

    At the moment I've got myself a nice little scene, a first person controller with a flashlight. And the ability to pick up batteries to keep the light going on, indicator and toggle on/off. However, this is not really how I want to have it working in the end;

    Now, the value of the max battery life equals 1, counting down by 0.01 until it's empty.
    If I collect a battery now, the max value (as can be seen in the flashlight object inspector while playing) just add's the max value 1 to the power that's left at the moment. For example when the power that's left is 0.8 and I pick up a battery, it becomes 1.8 so it overruns the max value. The indicator stays full until it drops below the max value of 1.

    What I want is the max value never to be able to be higher than 1.
    The batteries to be collectible and count in sort of a small 1/10 ( if maximum of 10 can be carried) in a small gui. Of course this way they should also be also reloaded manually whenever the player wants (so it's possible to walk around win an empty flashlight while having a couple of batteries in your pocket should be possible) instead of add juice to the flashlight immediately after picking up a battery like now, to get things work nicely...

    I hope I explained the issue right this way.
    My question, is this really hard to accomplish for a relatively new Unity user with not so much experience...? And maybe a little help in the right direction how to get started/do this?

    Thanks in advance!
     
  2. MaxRoetzler

    MaxRoetzler

    Joined:
    Jan 3, 2010
    Posts:
    136
    Sort of hard to say without seeing any of your code. Shouldn't be to difficult, but you can go from "Making the flashlight work" to "implementing an inventory system". Whereas the latter is a bit more complicated, but if you plan on adding other items and systems, it might be worth it.

    Generally, instead of increasing the energy value of the flashlight directly, you'll need to go through a battery storage or battery counter, and only increase the energy once you 'use' one of the batteries.
     
  3. RichardUnity

    RichardUnity

    Joined:
    Jan 3, 2016
    Posts:
    13
    Zortech thanks for your reply.
    You've got exactly the right picture of what I want to accomplish. At the moment I'm on my Mobile device but tonight I can post (parts of?) my code so far of course if needed.

    In the end there should be collectable batteries, keys and kind of letters to gather so your idea fits great in the picture. Only thing is that I'm just a starter with unity and coding especially, so I might find things complicated while they may be not that difficult after all. Because of that I want to thank you in advance for any help!

    It would be nice if its possible to see those spare batteries(and maybe keys too), and the number collected can be seen on the main game screen, so it's easy for the player to see he seems to get in trouble when 'in the heat of the game', instead of a separate inventory-screen.
    The letters only tell the story while playing so are not very important to be able the keep. They may be 'destructed after reading! So only two collectibles are really needed.

    Can you please tell me exactly what parts of code or information you need to see, so I can post this after work tonight!
     
  4. MaxRoetzler

    MaxRoetzler

    Joined:
    Jan 3, 2010
    Posts:
    136
    Hey,

    I was just asking for samples to get an idea of what level you're at, as like I've said this can be solved in various complexities and difficulties.

    Are the key's unique? Aka. do they only match a specific lock?

    It would be good to see the flashlight script, and how it uses 'batteries'.
     
  5. Racm_Games

    Racm_Games

    Joined:
    Sep 23, 2015
    Posts:
    19
    Well there are several approaches for what you want to accomplish...

    For the max value you mention in the first post, you could try something like this:
    (Assuming you have a current value and a Max value for the flashLight intensity)
    Code (CSharp):
    1.  
    2. if ( currentFlashValue < 1 )
    3. {
    4.    float tempValue = 0;
    5.    tempValue = maxFlashValue - currentFlashValue;
    6.    currentFlashValue += tempValue
    7. }
    8.  
    For the inventory ( batteries and keys )
    You may need to try modelling these in different scripts ( or one ), so you may have arrays of these items and when colliding with them you add them to the array, that will make a very simple "inventory". And that way if you want to have specific keys you may have a keyID value that when the player interacts with a door it checks the array of keys you have for the one that has the same KeyID that the door has. This way you may also change the charge value of the batteries so that instead of all batteries giving full charge, some give less.

    About the gui, you may want to watch tutorials to have it more clear but a very simple way will be to create a GameGUI script that contains methods to change the text value of UI text objects in the scene. So you can call the gameGUi script in the class that handles how many batteries and keys you have and pass through parameters the current values.
     
  6. RichardUnity

    RichardUnity

    Joined:
    Jan 3, 2016
    Posts:
    13
    Thank you guys for the help you're offering!
    Sure enough my skill level is 'beginner'... I'm working myself trough tutorials, this forums, etc. To learn the basics of Unity, but slowely I'm beginning to understand things by trial and error.

    About the keys (that I have to implent at the moment; I'm buissy figuring out the flashlight battery pickup system right now first, but in the end it would be the idea to be able to pickup several different keys for several different locks..

    And about the flashlight; this is my flashlight script for now:
    Code (JavaScript):
    1. #pragma strict
    2.  
    3. var flashlightLightSource : Light;
    4. var lightOn : boolean = true;
    5. var lightDrain : float = 0.1;
    6. private static var batteryLife : float = 0.0;
    7. var maxBatteryLife : float = 2.0;
    8.  
    9. private static var batteryPower : float = 1;
    10.  
    11. var barDisplay : float = 0;
    12. var pos : Vector2 = new Vector2(20,40);
    13. var size : Vector2 = new Vector2(60,20);
    14. var progressBarEmpty : Texture2D;
    15. var progressBarFull : Texture2D;
    16.  
    17. var soundTurnOn : AudioClip;
    18. var soundTurnOff : AudioClip;
    19.  
    20.  
    21. function Start()
    22. {
    23.     batteryLife = maxBatteryLife;
    24.     flashlightLightSource = GetComponent(Light);
    25. }
    26.  
    27.  
    28. static function AlterEnergy (amount : int)
    29. {
    30.     batteryLife = Mathf.Clamp(batteryLife+batteryPower, 0, 100);
    31.  
    32. }
    33.  
    34.  
    35.  
    36. function Update()
    37. {
    38.  
    39. //BATTERY LIFE BRIGHTNESS CYCLE//////////
    40.     if(lightOn && batteryLife >= 0)
    41.     {
    42.         batteryLife -= Time.deltaTime * lightDrain;
    43.     }
    44.         if(lightOn && batteryLife <= 0.4)
    45.     {
    46.         flashlightLightSource.GetComponent.<Light>().intensity = 5;
    47.     }
    48.         if(lightOn && batteryLife <= 0.3)
    49.     {
    50.         flashlightLightSource.GetComponent.<Light>().intensity = 4;
    51.     }
    52.     if(lightOn && batteryLife <= 0.2)
    53.     {
    54.         flashlightLightSource.GetComponent.<Light>().intensity = 3;
    55.     }
    56.         if(lightOn && batteryLife <= 0.1)
    57.     {
    58.         flashlightLightSource.GetComponent.<Light>().intensity = 2;
    59.     }
    60.             if(lightOn && batteryLife <= 0)
    61.     {
    62.         flashlightLightSource.GetComponent.<Light>().intensity = 0;
    63.     }
    64.  
    65.  
    66.  
    67.     barDisplay = batteryLife;
    68.  
    69.     if(batteryLife <= 0)
    70.     {
    71.         batteryLife = 0;
    72.         lightOn = false;
    73.     }
    74.  
    75.     if(Input.GetKeyUp(KeyCode.F))
    76.     {
    77.         toggleFlashlight();
    78.         toggleFlashlightSFX();
    79.      
    80.         if(lightOn)
    81.         {
    82.             lightOn = false;
    83.         }
    84.         else if (!lightOn && batteryLife >= 0)
    85.         {
    86.             lightOn = true;
    87.         }
    88.     }
    89. }
    90.  
    91.     /////// STATUS BAR DRAWING  ///////////
    92. function OnGUI()
    93. {
    94.     // draw the background:
    95.      GUI.BeginGroup (new Rect (pos.x, pos.y, size.x, size.y));
    96.         GUI.Box (Rect (0,0, size.x, size.y),progressBarEmpty);
    97.         // draw the filled-in part:
    98.         GUI.BeginGroup (new Rect (0, 0, size.x * barDisplay, size.y));
    99.             GUI.Box (Rect (0,0, size.x, size.y),progressBarFull);
    100.              GUI.EndGroup ();
    101.     GUI.EndGroup ();
    102. }
    103.    
    104. function toggleFlashlight()
    105. {
    106.     if(lightOn)
    107.     {
    108.         flashlightLightSource.enabled = false;
    109.     }
    110.     else
    111.     {
    112.         flashlightLightSource.enabled = true;
    113.     }
    114. }
    115. function toggleFlashlightSFX()
    116. {
    117.     if(flashlightLightSource.enabled)
    118.     {
    119.         GetComponent.<AudioSource>().clip = soundTurnOn;
    120.     }
    121.     else
    122.     {
    123.         GetComponent.<AudioSource>().clip = soundTurnOff;
    124.     }
    125.     GetComponent.<AudioSource>().Play();
    126.  
    127. }
    128.  
    129.     @script RequireComponent(AudioSource)
    130.  
    131.      
    132.              
    133.  
    134.    
    And this is the Battery one:
    Code (JavaScript):
    1. var buttonInRange;
    2. var buttonActivated;
    3. var batterySound : AudioClip;
    4. private static var batteryPower : float = 10;
    5.  
    6. public var guiSkin : GUISkin;
    7.  
    8. private var hasPlayed = false;
    9.  
    10. function OnTriggerEnter (c : Collider)
    11. {
    12.     buttonInRange = true;
    13.  
    14. }
    15. function OnTriggerExit (c : Collider)
    16. {
    17.     buttonInRange = false;
    18.  
    19. }
    20. function OnGUI ()
    21. {
    22.     if(buttonInRange == true)
    23.     {
    24.         GUI.skin = guiSkin;
    25.         GUI.Label (Rect (Screen.width/2-50, Screen.height/2-55, 120, 50), "Pick up batteries");
    26.  
    27.     }
    28.  
    29. }
    30. function Update ()
    31. {
    32.     if (buttonInRange == true)
    33.     {
    34.         if (Input.GetKeyDown ("e"))
    35.         {
    36.             if(!hasPlayed)
    37.             {
    38.                 AudioSource.PlayClipAtPoint(batterySound, transform.position);
    39.                 FlashLight.AlterEnergy(batteryPower);
    40.                 Destroy(gameObject);
    41.                 hasPlayed = true;
    42.          
    43.             }
    44.      
    45.         }
    46.  
    47.     }
    48.  
    49. }

    I hope this will do...!
     
  7. RichardUnity

    RichardUnity

    Joined:
    Jan 3, 2016
    Posts:
    13
    Didn't get to figure it out in the meantime..
    I ended up with one error after another and eventually a useless flashlight.
    But still hope to get it right sometime!

    Also I fount this C# script I tried to implant to make my batteries collectible, but that wouldn't work out very well either. So I'm kinda stuck and back where I started right now. Anyone any suggestions how I could modifie my scripts the right way?

    The code I found;
    Code (CSharp):
    1. Code (csharp):
    2. using UnityEngine;
    3. using System.Collections;
    4. public class collectableDestroy : MonoBehaviour {
    5.     private int collected = 0; //Set up a variable to store how many you've collected
    6.     public AudioClip collectedSound;     //This is the sound that will play after you collect one
    7.  
    8.     //This is the text that displayed how many you've collected in the top left corner
    9.     void OnGUI(){
    10.         GUI.Label(new Rect(10, 10, 50, 20), "Spare Batteries:" + collected);
    11.     }
    12.     private void OnTriggerEnter(Collider other){ //Checks to see if you've collided with another object
    13.         if(other.CompareTag("collectable")){ //checks to see if this object is tagged with "collectable"
    14.             audio.PlayOneShot(collectedSound); //plays the sound assigned to collectedSound
    15.             collected++; //adds a count of +1 to the collected variable
    16.             Destroy(other.gameObject); //destroy's the collectable
    17.         }
    18.     // Use this for initialization
    19.     void Start () {
    20.  
    21.     }
    22.  
    23.     // Update is called once per frame
    24.     void Update () {
    25.  
    26.     }
    27.     }
    28.  
    And the purpose once more;

    *Being able to collect multiple batteries, maximum of 5 for instance.
    *Showing the count on GUI.
    *Reload them manually instead of instantly fill up flashlight when picked up a battery.
    *Prevent flashlight from being loaded more than max value of 100%.
    (So if flashlight is full for 80% and you press [R]eload, it just counts off one battery and fills up flashlight to 100%).

    Thank you very much for helping me out...I'm really stuck a.t.m.