My slow-healing script gets faster and faster (C# / Unity)

unity health regeneration
health regeneration script
how to make unity run faster
unity scripting techniques
unity script optimization
unity c# profiler
unity faster compile
unity make builds faster

I am making a FPS zombie game that is essentially a rip off of COD Nazi Zombies. I am 2 months into self-learning Unity with C# and everything is going well, however this small issue is bugging me and I could use a hand.

The Problem : The players health heals far too fast nomatter what values I change healingAmount and healingFreq to. Furthermore, the health seems to increasingly get faster. Is there an better way of writing a self heal method than to use a Coroutine?

Relevent code below...

public int currentHealth = 100;
public int maxHealth = 100;
public int healingAmount = 1;
public int healingFreq = 1;

public void Start()
{
    SetHealthBar(currentHealth);
}

public void Update()
{
    StartCoroutine(SlowHeal());
}

    IEnumerator SlowHeal()
{
    while (currentHealth < maxHealth) 
    {
        yield return new WaitForSeconds(healingFreq); // Stops loop for a desired amount of seconds at a time.
        currentHealth += healingAmount; // Adds the desired healing amount to the players current health.
        SetHealthBar(currentHealth); // Updates healthbar to the players current health.

        if (currentHealth > maxHealth) // Limits the healing to the max in the event it may overflow
        {
            currentHealth = maxHealth;
        }
    }
}

You only need to call StartCoroutine() method once in your Start method. StartCoroutine() will handle regular calls to SlowHeal(). Try moving your StartCoroutine() call to your Start method and see how things pan out.

Regenerating Health Over Time., 0. Question by davidflynn2 � Dec 23, 2012 at 12:37 AM � c# I am trying to make it so that the health of my ship will regenerate health I have the following code but all it does is add 1 health repeadly realy fast. A better way to do that is to set the auto healing feature in a coroutine started Shorten C# Script 2 Answers. 2 Google Play Rejects My App For Unsafe Cryptographic Encryption Patterns Dec 9 '19 1 My slow-healing script gets faster and faster (C# / Unity) Dec 9 '19 1 When adding first node to linked list in hashmap, why must the new node be assigned directly to the indexed pointer?

Once the zombie has healed once, there is no way to start the healing process again. I would propose the following.

public void Update()
{
    if ( ( currentHealth < maxHealth ) && !healing )
    {
        healing = true;
        StartCoroutine(SlowHeal());
   }
}

IEnumerator SlowHeal()
{
    while (currentHealth < maxHealth) 
    {
        yield return new WaitForSeconds(healingFreq);

        currentHealth += healingAmount;
        if (currentHealth > maxHealth)
        {
            currentHealth = maxHealth;
        }

        SetHealthBar(currentHealth);
    }

    healing = false;
}

Performance issues. How fast is C# in Unity compared to say, native , I was just trying to get this up and running as a proof of concept that is easy to Is C# in Unity in the general vicinity of being as fast as compiled C++? Will my code run much slower when I am running it in the editor versus building it as a final project? None of my C# script interfere with the game speed. This banner text can have markup.. web; books; video; audio; software; images; Toggle navigation

Topher is basically correct in his assessment on what's happening, but I would write the code differently. Likewise Chris Walsh is correct in saying you only need to call StartCoroutine in Start.

public void Start()
{
    SetHealthBar(currentHealth);
}

IEnumerator SlowHeal()
{
    while (true) 
    {
        yield return new WaitForSeconds(healingFreq);

        currentHealth += healingAmount;
        if (currentHealth > maxHealth)
        {
            currentHealth = maxHealth;
        }

        SetHealthBar(currentHealth);
    }
}

Because the zombie will always heal once it is not at full health, there is no reason to terminate the coroutine when the zombie reaches full health: the code is already there to insure the zombie doesn't heal above maximum, so further healing and no healing are effectively identical.

In this way the coroutine can be started once (in Start) and never needs to be messed with after that. No checking for whether or not the coroutine is already running, no more bools to insure we don't start a second cortoutine, nothing special is needed if we insure that the coroutine itself never exits (coroutines are automatically stopped when the script is disabled or destroyed*).

*This does not apply to coroutines started by other, non-self objects.

How to get faster script compilation?, I also have wondered if compilation time is slower for javascript than C#. Most of my scripts are in javascript. It would be a pretty big task to� This banner text can have markup.. web; books; video; audio; software; images; Toggle navigation

Optimizing Scripts - Unity, Attempting to develop something which is fast from the beginning is risky, Finally, we have one more problem - this script does a lot, and its getting slow! Instead of spending 45 minutes on the elliptical and even more time on weights bored out of my mind, I'm doing burpees, squats, push ups, plank exercises and more in a circuit that really gets my heart rate up, metabolism working and strengthening my muscles at the same time, all in a short workout!

Recover project from build unity, I like to use one dedicated folder to hold all my Unity projects. with Unity GameObjects as usual, and get great performance benefits at runtime. But the recovery challenge today calls for Jun 24, 2020 � The project aims to capture 3 a box to an empty scene and create a new C# script “Quicksand” attached to the box.

Unity explosion 2d, Find out how the Unity helped her tackle the technical challenges involved off on a timer, some modifications to the prefabs to get explosions of different sizes, one script onto your GameObject, and call its Explode() method* Create fast I am attempting to create a 2D game in Unity using C# as my scripting language.

Comments
  • You are launching a new coroutine every time Update is called. Update is called many, many times per second.
  • Good eye, thank you. I can now understand why the healing was getting faster and faster. Because the slowHeal() was essentially being copied once per frame.
  • @DonalC93 See the code in my answer to insure that the coroutine continues to run after the zombie reaches maximum health.
  • I concur with @DonalC93 that their version allows later damage to start healing again which is what you are probably aiming to do.
  • This was a great addition. It also helped solve the issue of the healthbar reading 102% instead of 100%, because the healthbar in my code was updated before the health-correction. Thanks.
  • This is a reasonable alternative. I'm not sure how the zombie actually "dies" in either of our implementations, but that's beyond the scope of the question. ;-)
  • Just noodling on this... in either of our implementations a check for "currentHealth > 0" could be used as a death-check.
  • Or you check when the damage is dealt (which will always be before the coroutine gets another update).
  • Very true. However, in the damage check you may want to cut off the SlowHeal process (or have SlowHeal end itself) so that you don't have the zombies "springing back to life" when they were thought to have been destroyed (although, that might be the desired effect). Obviously, I am extrapolating a much larger solution than the question asked.
  • @Topher *nodnod*