Y
Y
yraiv2022-03-16 11:36:10
Unity
yraiv, 2022-03-16 11:36:10

Why is the variable set to 0?

I want to implement burning, namely the gradual infliction of damage, every n seconds to remove hp. Why is it zeroing out my values ​​when running a caroutine

void OnTriggerEnter2D(Collider2D collider)
    {
        if (collider.gameObject.tag == "FireBullet")
        {
            fireDamage = collider.gameObject.GetComponent<FireDamage>().atack; // получаю 4
            timeBurn = collider.gameObject.GetComponent<FireDamage>().TimeFire; // получаю 4
            ThistimeBurn = 0;
            Burning();
        }

    }

IEnumerator Burning()
    {
        Debug.Log(timeBurn); // получаю 0


        if (timeBurn > ThistimeBurn)
        {

            health = -fireDamage;
            ThistimeBurn = +Time.deltaTime;


            yield return new WaitForSecondsRealtime(1f);
            StartCoroutine(Burning());
        }

    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
K0TlK, 2022-03-16
@yraiv

This is done through coroutines or through tasks. Here is an example using a coroutine:

using System.Collections;
using UnityEngine;

public class Fire : MonoBehaviour
{

    private void Start()
    {
        StartCoroutine(Burn(5f, 1f));
    }

    private IEnumerator Burn(float time, float damageInterval)
    {
        while (time > 0)
        {
            time -= damageInterval;
            Debug.Log("ApplyDamage");
            yield return new WaitForSeconds(damageInterval);
        }

        yield break;
    }
}

In the start method, I start the coroutine. The coroutine itself, in my case, will write a log every damageInterval seconds for time. yield break is needed so that the coroutine ends after the loop is completed.

F
Farawa, 2022-03-16
@Farawa

because in the trigger you get data from the object, and in the coroutine xs from where, you still don’t start the coroutine in principle, it’s better to start the coroutine on the object that will burn, pass this object to the coroutine to change its data

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question