- Home /
Reduce health for everyone ??
[SerializeField] float toReduce;
[SerializeField] float reduceEvery = 1;
float timer1 ,timer2;
private void Update() {
timer1 = Mathf.Max(0, timer1 + Time.deltaTime);
timer2 = Mathf.Max(0, timer2 + Time.deltaTime);
}
private void OnTriggerStay(Collider other) {
if (other.CompareTag("Player")) {
if (timer1 >= reduceEvery) {
other.GetComponent<PlayerHealth>().ReduceHealth(toReduce);
timer1 = 0;
}
}
if (other.CompareTag("Enemy")) {
if (timer2 >= reduceEvery) {
other.GetComponent<EnemyHealth>().ReduceHealth(toReduce);
timer2 = 0;
}
}
}
it works for 1 player and 1 enemy but not if add more enemy, i thinks its because timer right ?, but it so waste if i add timer for everyone, so how can i reduce every one who touch or stay in collider ?
Comment
Best Answer
Answer by logicandchaos · Aug 07, 2021 at 05:16 PM
It's because you are setting timer2 to zero in the collision, set it to zero in update instead.
move this to update:
if (timer2 >= reduceEvery) { timer2 = 0; }
You could also use OverlapCircleAll() in update rather than OnTriggerStay and it should be more efficient.
Overlap sphere too is a collider, it can get all the elements currently in range of a sphere through an array