Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
This question was closed Apr 27 at 07:08 PM by pwolf1897.
avatar image
0
Question by pwolf1897 · Nov 25, 2021 at 04:02 PM · flashlightfastbattery

Battery Script If someone know the asnwer please help !!

I tried to make a Flashlight Battery Script but it's dont work. Can someone help me? -BATTERY SCRIPT:

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class Baterias : MonoBehaviour { public Flashlight flashlight;

 [SerializeField] public int batteries = 2;

 public void OnTriggerEnter(Collider other)
 {
     if (other.CompareTag("Player"))
     {

         GameObject.FindGameObjectWithTag("Flashlight").GetComponent<Flashlight>().batteries = 2;
         flashlight.batteries += 2;


         Destroy(this.gameObject);

     }
 }

}

-FLASHLIGHT SCIRPT:

using System.Collections; using System.Text; using TMPro; using UnityEngine; using UnityEngine.UI;

[RequireComponent(typeof(Light))] [RequireComponent(typeof(AudioSource))] public class Flashlight : MonoBehaviour { #region Parameters

 [SerializeField] KeyCode reloadKey = KeyCode.R;
 [SerializeField] KeyCode toggleKey = KeyCode.F;

 [SerializeField] int maxBatteries = 4;
 [SerializeField] public int batteries = 2;

 [SerializeField] bool autoReduce = true;
 [SerializeField] float reduceSpeed = 1.0f;

 [SerializeField] bool autoIncrease = false;
 [SerializeField] float increaseSpeed = 0.5f;

 [Range(0, 1)]
 [SerializeField] float toggleOnWaitPrecentage = 0.05f;

 public const float minBatteryLife = 0.0f;
 [SerializeField] float maxBatteryLife = 10.0f;

 [SerializeField] float followSpeed = 5.0f;
 [SerializeField] Quaternion offset = Quaternion.identity;

 #endregion

 #region References 

 [SerializeField] AudioClip onSound = null;
 [SerializeField] AudioClip offSound = null;
 [SerializeField] AudioClip reloadSound = null;

 [SerializeField] Image stateIcon = null;
 [SerializeField] Slider lifeSlider = null;
 [SerializeField] Image lifeSliderFill = null;
 [SerializeField] TextMeshProUGUI reloadText = null;
 [SerializeField] TextMeshProUGUI countText = null;
 [SerializeField] CanvasGroup holder = null;

 [SerializeField] Color fullLifeColor = Color.green;
 [SerializeField] Color outLifeColor = Color.red;

 [SerializeField] new Camera camera = null;
 [SerializeField] GameObject flashlight = null;

 #endregion

 #region Statistics

 [SerializeField]
 private float batteryLife = 0.0f;
 [SerializeField]
 private bool usingFlashlight = false;
 [SerializeField]
 private bool outOfBattery = false;

 #endregion

 #region Private and Properties

 private IEnumerator IE_UpdateBatteryLife = null;

 Light _light = null;
 Light Light
 {
     get
     {
         if (_light == null)
         {
             _light = GetComponent<Light>();
             if (_light == null) { _light = gameObject.AddComponent<Light>(); }
             _light.type = LightType.Spot;
         }
         return _light;
     }
 }

 float defaultIntensity = 0.0f;

 AudioSource _source = null;
 AudioSource Source
 {
     get
     {
         if (_source == null)
         {
             _source = GetComponent<AudioSource>();
             if (_source == null) { _source = gameObject.AddComponent<AudioSource>(); }
             _source.playOnAwake = false;
         }
         return _source;
     }
 }

 float GetLifePercentage
 {
     get
     {
         return batteryLife / maxBatteryLife;
     }
 }
 float GetLightIntensity
 {
     get
     {
         return defaultIntensity * GetLifePercentage;
     }
 }

 bool CanReload
 {
     get
     {
         return usingFlashlight && (batteries > 0 && batteryLife < maxBatteryLife);
     }
 }
 bool MoreThanNeededPercetage
 {
     get
     {
         return GetLifePercentage >= toggleOnWaitPrecentage;
     }
 }

 #endregion 

 private void Start()
 {
     Init();
 }

 private void Update()
 {
     if (Input.GetKeyDown(toggleKey))
     {
         ToggleFlashlight(!usingFlashlight, true);
     }
     if (Input.GetKeyDown(reloadKey) && CanReload)
     {
         Reload();
     }
     if (usingFlashlight)
     {
         transform.localRotation = Quaternion.Slerp(transform.localRotation, camera.transform.localRotation * offset, followSpeed * Time.deltaTime);
         flashlight.transform.rotation = transform.rotation;
     }
 }

 private void Reload()
 {
     batteryLife = maxBatteryLife;
     Light.intensity = GetLightIntensity;
     batteries--;

     UpdateCountText();
     UpdateSlider();

     UpdateBatteryState(false);
     UpdateBatteryLifeProcess();

     PlaySFX(reloadSound);
 }

 void ToggleFlashlight(bool state, bool playSound)
 {
     usingFlashlight = state;
     flashlight.SetActive(state);

     state = (outOfBattery && usingFlashlight) ? false : usingFlashlight;
     ToggleObject(state);

     if (holder)
     {
         switch (usingFlashlight)
         {
             case true:
                 holder.alpha = 1.0f;
                 holder.blocksRaycasts = true;
                 break;
             case false:
                 holder.alpha = 0.0f;
                 holder.blocksRaycasts = false;
                 break;
         }
     }

     if (playSound)
     {
         PlaySFX(usingFlashlight ? onSound : offSound);
     }

     UpdateBatteryLifeProcess();
 }

 private void UpdateBatteryLifeProcess()
 {
     if (IE_UpdateBatteryLife != null) { StopCoroutine(IE_UpdateBatteryLife); }

     if (usingFlashlight && !outOfBattery)
     {
         if (autoReduce)
         {
             IE_UpdateBatteryLife = ReduceBattery();
             StartCoroutine(IE_UpdateBatteryLife);
         }
         return;
     }
     if (autoIncrease)
     {
         IE_UpdateBatteryLife = IncreaseBattery();
         StartCoroutine(IE_UpdateBatteryLife);
     }
 }

 private IEnumerator IncreaseBattery()
 {
     while (batteryLife < maxBatteryLife)
     {
         var newValue = batteryLife + increaseSpeed * Time.deltaTime;
         batteryLife = Mathf.Clamp(newValue, minBatteryLife, maxBatteryLife);
         Light.intensity = GetLightIntensity;

         BatteryLifeCheck();

         UpdateSlider();

         yield return null;
     }
 }

 private void BatteryLifeCheck()
 {
     if (MoreThanNeededPercetage && outOfBattery)
     {
         UpdateBatteryState(false);
         UpdateBatteryLifeProcess();
     }
 }

 private IEnumerator ReduceBattery()
 {
     while (batteryLife > 0.0f)
     {
         var newValue = batteryLife - reduceSpeed * Time.deltaTime;
         batteryLife = Mathf.Clamp(newValue, minBatteryLife, maxBatteryLife);

         Light.intensity = GetLightIntensity;

         UpdateSlider();

         yield return null;
     }
     UpdateBatteryState(true);
     UpdateBatteryLifeProcess();
 }

 private void UpdateBatteryState(bool isDead)
 {
     outOfBattery = isDead;

     if (reloadText)
     {
         reloadText.enabled = isDead;
     }
     if (stateIcon) { stateIcon.color = isDead ? new Color(1, 1, 1.5f) : Color.white; }

     var state = outOfBattery ? false : usingFlashlight;
     ToggleObject(state);
 }

 private void PlaySFX(AudioClip clip)
 {
     if (clip == null) { return; }

     Source.clip = clip;
     Source.Play();
 }

 void ToggleObject(bool state)
 {
     Light.enabled = state;
 }

 void UpdateSlider()
 {
     if (lifeSlider) { lifeSlider.value = batteryLife; }
     if (lifeSliderFill)
     {
         lifeSliderFill.color = Color.Lerp(outLifeColor, fullLifeColor, GetLifePercentage);
     }
 }
 void UpdateCountText()
 {
     if (countText)
     {
         StringBuilder countString = new StringBuilder("Batteries: ");
         countString.Append(batteries);
         countString.Append(" / ");
         countString.Append(maxBatteries);

         countText.text = countString.ToString();
     }
 }

 private void Init()
 {
     defaultIntensity = Light.intensity;
     batteryLife = maxBatteryLife;

     UpdateBatteryState(false);

     ToggleFlashlight(false, false);

     UpdateCountText();

     lifeSlider.minValue = minBatteryLife;
     lifeSlider.maxValue = maxBatteryLife;
     lifeSlider.value = batteryLife;
     UpdateSlider();

     if (!camera)
     {
         camera = Camera.main;
     }
     reloadText.text = "RELOAD(" + reloadKey + ")";
 }

}

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

  • Sort: 
avatar image
0
Best Answer

Answer by BrokeLol · Nov 27, 2021 at 09:33 AM

Check if your flashlight has a box collider/sphere collider and then tick the "isTrigger" box. It should probably work but If it doesn't have any collider, go to add component search "box collider" if it is cube shaped or "sphere collider" if it is sphere shaped. If this doesn't work see if your player has the tag you have written

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image pwolf1897 · Nov 27, 2021 at 11:59 AM 0
Share

THANK YOU!! Thanks for everybody i fixed it.. In battery script i change to this: public void OnTriggerEnter(Collider other) { if (other.CompareTag("Capsule")) { other.GetComponentInChildren().batteries += 2; flashlight.batteries += 1; Destroy(this.gameObject); } }

And i added a "UpdateCountText();" to "private void Update()" in Flaslight. Also i added a box collider to the flashlight and set it "trigger". And last i added a "capsule" tag to player.

Anyways thanks for everybody.

avatar image
0

Answer by JethRow · Nov 26, 2021 at 02:41 AM

@pwolf1897 , can you try this out?

 public void OnTriggerEnter(Collider other)
 {
     if (other.transform.tag=="Player")
     {
         other.GetComponent<Flashlight>().batteries += 2;
         Destroy(this.gameObject);
     }
 }

But in Case that Flashlight script is in child of object that has collider just set

 other.GetComponentInParent<Flashlight>().batteries += 2;

Or if Flashlight script is a child of your object that has collider that triggers it then set

 other.GetComponentInChildren<Flashlight>().batteries += 2;

Also this will only work if ur collider that triggers the battery collider is on the same object as the flashlight Script,and check if the collider on the battery is set as trigger! Also remember to check if collider on your player is tagged as "Player" this must be exactly same!

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by pwolf1897 · Nov 26, 2021 at 09:04 PM

@JethRow It's doesn't work. :( I Upload some ScreenShots maybe it can help. Here's more screenshots: https://fastupload.co/1110904


kepernyokep-2021-11-26-215519.png (367.6 kB)
kepernyokep-2021-11-26-215527.png (363.1 kB)
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Follow this Question

Answers Answers and Comments

131 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Flashlight Battery Error No definition 1 Answer

How do you write a Pauseable-Timer Script in Unity JavaScript? 1 Answer

Flashlight battery indicator 1 Answer

Recharging battery script, help 1 Answer

How to make a GUI to show how much battery is left on Flashlight? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges