- Home /
Question by
freakymango1 · Jan 16, 2017 at 08:14 AM ·
c#spotlightflashlighthorrorbattery
How do I make a power out on my flashlight?
What I want to have is a power out feature in my flashlight. I have this in c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class flashlight : MonoBehaviour {
public Light YourFlashlight;
public AudioClip FlashlightSoundOn;
public AudioClip FlashlightSoundOff;
public AudioSource TheAudioSource;
private bool isActive;
// Use this for initialization
void Start ()
{
isActive = true;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
if(isActive == false) //Flashlight on
{
YourFlashlight.enabled = true;
isActive = true;
TheAudioSource.PlayOneShot(FlashlightSoundOn);
}
else if(isActive == true) //Flashlight off
{
YourFlashlight.enabled = false;
isActive = false;
TheAudioSource.PlayOneShot(FlashlightSoundOff);
}
}
}
}
How can I add a script so if you waste too much battery it will shut down. (makes a challenge of staying alive and conserving battery! :D)
Comment
Answer by Ambrose998800 · Jan 16, 2017 at 08:56 AM
Try that:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class flashlight : MonoBehaviour
{
public Light YourFlashlight;
public AudioClip FlashlightSoundOn;
public AudioClip FlashlightSoundOff;
public AudioSource TheAudioSource;
public float BatteryCharge;
public float PowerDrain;
private bool isActive;
// Use this for initialization
void Start()
{
isActive = true;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
if (isActive == false && BatteryCharge > 0) //Flashlight on
{
YourFlashlight.enabled = true;
isActive = true;
TheAudioSource.PlayOneShot(FlashlightSoundOn);
}
else if (isActive == true) //Flashlight off
{
YourFlashlight.enabled = false;
isActive = false;
TheAudioSource.PlayOneShot(FlashlightSoundOff);
}
}
if (BatteryCharge <= 0) //Flashlight off
{
YourFlashlight.enabled = false;
isActive = false;
TheAudioSource.PlayOneShot(FlashlightSoundOff);
}
if ((isActive == true)
{
BatteryCharge = BatteryCharge - Time.deltaTime * PowerDrain;
}
}
}
Your answer
Follow this Question
Related Questions
Flashlight pickup, battery etc 3 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Luz parpadeante con bateria 0 Answers
Flashlight battery script 3 Answers