Making a slider, slider does nothing even when attached to the script?
Here's the script I'm using: (Got it with the help of (@Hellium))
using System.Collections; using System.Collections.Generic; using UnityEngine;
[System.Serializable] public class LightEvent : UnityEngine.Events.UnityEvent { }
public class FlashLight : MonoBehaviour { public GameObject flashLight; public LightEvent OnBatteryChanged;
public float battery = 10f;
private float Battery
{
get { return battery; }
set
{
battery = Mathf.Clamp(value, 0, 10);
OnBatteryChanged?.Invoke(value);
}
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.F) && flashLight.activeInHierarchy)
{
flashLight.SetActive(false);
}
else if (Input.GetKeyDown(KeyCode.F) && !flashLight.activeInHierarchy)
{
flashLight.SetActive(true);
}
if (flashLight.activeInHierarchy)
{
battery -= Time.deltaTime;
}
if (battery < 0)
{
battery = 0;
Destroy(flashLight.gameObject);
}
}
}
Answer by Hellium · Oct 07, 2019 at 09:49 PM
You have to use the property setter, not change the variable itself:
if (flashLight.activeInHierarchy)
{
Battery -= Time.deltaTime;
}
if (Battery < 0)
{
Battery = 0;
Destroy(flashLight.gameObject);
}
And here is a little tip
Replace
if (Input.GetKeyDown(KeyCode.F) && flashLight.activeInHierarchy)
{
flashLight.SetActive(false);
}
else if (Input.GetKeyDown(KeyCode.F) && !flashLight.activeInHierarchy)
{
flashLight.SetActive(true);
}
By
if (Input.GetKeyDown(KeyCode.F))
{
flashLight.SetActive(!flashLight.activeSelf);
}
It will do the same as before, but with less code and more efficiently
You're an angle ;( ;( ;( ;( ;( ;( ;( ;( ;( ;( ;( Thank you, I really wish I could repay you but I'm not good at anything <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3 <3
Your answer
Follow this Question
Related Questions
How to assign slider to float: Spin, on a gameobject 1 Answer
Slider graphic refuses to update with value 1 Answer
Prefab UI Slider misses the fill and background items... 0 Answers
I need help fixing my movement/jetpack script, it involves a slider. 0 Answers
Swapping characters breaks controls 0 Answers